iOS开发基础-图片切换(4)之懒加载

时间:2023-03-08 17:53:59

延续:iOS开发基础-图片切换(3),对(3)里面的代码用懒加载进行改善。

一、懒加载基本内容

  懒加载(延迟加载):即在需要的时候才加载,修改属性的 getter 方法。

  注意:懒加载时一定要先判断该属性是否为 nil ,如果为 nil 才进行实例化。

优点:

  1) viewDidLoad 中创建对象的方法用懒加载创建,增加可读性。

  2)每个控件的 getter 方法中负责各自的实例化处理,增加代码之间的独立性。

二、代码实例

  简化 viewDidLoad 方法如下:

 - (void)viewDidLoad {
[super viewDidLoad];
[self change]; //初始化界面
}

  对2个 UILabel ,2个 UIButton 和1个 UIImageView 的 getter 方法进行修改:

 //firstLabel的getter方法
- (UILabel *)firstLabel {
//判断是否有了,若没有,则进行实例化
if (!_firstLabel) {
_firstLabel = [[UILabel alloc]initWithFrame:CGRectMake(, , , )];
[_firstLabel setTextAlignment:NSTextAlignmentCenter];
[self.view addSubview:_firstLabel];
}
return _firstLabel;
} //lastLabel的getter方法
- (UILabel *)lastLabel {
if (!_lastLabel) {
_lastLabel = [[UILabel alloc] initWithFrame:CGRectMake(, , , )];
[_lastLabel setTextAlignment:NSTextAlignmentCenter];
[self.view addSubview:_lastLabel];
}
return _lastLabel;
} //imageIcon的getter方法
- (UIImageView *)imageIcon {
if (!_imageIcon) {
_imageIcon = [[UIImageView alloc] initWithFrame:CGRectMake(POTOIMAGEX, POTOIMAGEY, POTOIMAGEWIDTH, POTOIMAGEHEIGHT)];
_imageIcon.image = [UIImage imageNamed:@"beauty0"];
[self.view addSubview:_imageIcon];
}
return _imageIcon;
} //leftButton的getter方法
- (UIButton *)leftButton {
if (!_leftButton) {
_leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
_leftButton.frame = CGRectMake(, self.view.center.y, , );
[_leftButton setBackgroundImage:[UIImage imageNamed:@"leftRow"] forState:UIControlStateNormal];
[self.view addSubview:_leftButton];
[_leftButton addTarget:self action:@selector(leftClicked:) forControlEvents:UIControlEventTouchUpInside];
}
return _leftButton;
} //rightButton的getter方法
- (UIButton *)rightButton {
if (!_rightButton) {
_rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
_rightButton.frame = CGRectMake(, self.view.center.y, , );
[_rightButton setBackgroundImage:[UIImage imageNamed:@"rightRow"] forState:UIControlStateNormal];
[self.view addSubview:_rightButton];
[_rightButton addTarget:self action:@selector(rightClicked:) forControlEvents:UIControlEventTouchUpInside];
}
return _rightButton;
}

参考博客:iOS开发UI篇—懒加载

实例代码:http://pan.baidu.com/s/1dElhMmP