延續:iOS開發基礎-圖片切換(3),對(3)裏面的代碼用懶加載進行改善。html
懶加載(延遲加載):即在須要的時候才加載,修改屬性的 getter 方法。ide
注意:懶加載時必定要先判斷該屬性是否爲 nil ,若是爲 nil 才進行實例化。spa
優勢:code
1) viewDidLoad 中建立對象的方法用懶加載建立,增長可讀性。orm
2)每一個控件的 getter 方法中負責各自的實例化處理,增長代碼之間的獨立性。htm
簡化 viewDidLoad 方法以下:對象
1 - (void)viewDidLoad { 2 [super viewDidLoad]; 3 [self change]; //初始化界面 4 }
對2個 UILabel ,2個 UIButton 和1個 UIImageView 的 getter 方法進行修改:blog
1 //firstLabel的getter方法 2 - (UILabel *)firstLabel { 3 //判斷是否有了,若沒有,則進行實例化 4 if (!_firstLabel) { 5 _firstLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 20, 300, 30)]; 6 [_firstLabel setTextAlignment:NSTextAlignmentCenter]; 7 [self.view addSubview:_firstLabel]; 8 } 9 return _firstLabel; 10 } 11 12 //lastLabel的getter方法 13 - (UILabel *)lastLabel { 14 if (!_lastLabel) { 15 _lastLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 400, 300, 30)]; 16 [_lastLabel setTextAlignment:NSTextAlignmentCenter]; 17 [self.view addSubview:_lastLabel]; 18 } 19 return _lastLabel; 20 } 21 22 //imageIcon的getter方法 23 - (UIImageView *)imageIcon { 24 if (!_imageIcon) { 25 _imageIcon = [[UIImageView alloc] initWithFrame:CGRectMake(POTOIMAGEX, POTOIMAGEY, POTOIMAGEWIDTH, POTOIMAGEHEIGHT)]; 26 _imageIcon.image = [UIImage imageNamed:@"beauty0"]; 27 [self.view addSubview:_imageIcon]; 28 } 29 return _imageIcon; 30 } 31 32 //leftButton的getter方法 33 - (UIButton *)leftButton { 34 if (!_leftButton) { 35 _leftButton = [UIButton buttonWithType:UIButtonTypeCustom]; 36 _leftButton.frame = CGRectMake(10, self.view.center.y, 30, 53); 37 [_leftButton setBackgroundImage:[UIImage imageNamed:@"leftRow"] forState:UIControlStateNormal]; 38 [self.view addSubview:_leftButton]; 39 [_leftButton addTarget:self action:@selector(leftClicked:) forControlEvents:UIControlEventTouchUpInside]; 40 } 41 return _leftButton; 42 } 43 44 //rightButton的getter方法 45 - (UIButton *)rightButton { 46 if (!_rightButton) { 47 _rightButton = [UIButton buttonWithType:UIButtonTypeCustom]; 48 _rightButton.frame = CGRectMake(280, self.view.center.y, 30, 53); 49 [_rightButton setBackgroundImage:[UIImage imageNamed:@"rightRow"] forState:UIControlStateNormal]; 50 [self.view addSubview:_rightButton]; 51 [_rightButton addTarget:self action:@selector(rightClicked:) forControlEvents:UIControlEventTouchUpInside]; 52 } 53 return _rightButton; 54 }
參考博客:iOS開發UI篇—懶加載圖片