延遲加載就是「等到真正需要時才建立」,以空間換取啟動效率。實作上寫的就是該屬性的 getter。
有一個絕對不能忘的前提:進入 getter 後要先判斷是否已存在,沒有的話才建立,否則每次存取都會產生一個新物件。
viewDidLoad,可讀性更高。先用巨集統一版面常數:
#define POTOIMGW 200 #define POTOIMGH 300 #define POTOIMGX 60 #define POTOIMGY 50 @interface YYViewController () @property (nonatomic, strong) UILabel *firstlab; @property (nonatomic, strong) UILabel *lastlab; @property (nonatomic, strong) UIImageView *icon; @property (nonatomic, strong) UIButton *leftbtn; @property (nonatomic, strong) UIButton *rightbtn; @property (nonatomic, strong) NSArray *array; @property (nonatomic, assign) int i; - (void)change; @end
刷新界面的邏輯獨立成一個方法,方便左右翻頁時重複呼叫:
- (void)viewDidLoad {
[super viewDidLoad];
[self change];
}
- (void)change {
[self.firstlab setText:[NSString stringWithFormat:@"%d/5", self.i + 1]];
// 這裡同時示範了「先 get 再 set」:存取屬性會觸發延遲加載
self.icon.image = [UIImage imageNamed:self.array[self.i][@"name"]];
self.lastlab.text = self.array[self.i][@"desc"];
self.leftbtn.enabled = (self.i != 0);
self.rightbtn.enabled = (self.i != 4);
}
各控件的 getter,每一個都是「先檢查、再建立、最後回傳」:
/** 1. 圖片序號標籤 */
- (UILabel *)firstlab {
if (!_firstlab) {
_firstlab = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 300, 30)];
[_firstlab setTextAlignment:NSTextAlignmentCenter];
[self.view addSubview:_firstlab];
}
return _firstlab;
}
/** 2. 圖片視圖 */
- (UIImageView *)icon {
if (!_icon) {
_icon = [[UIImageView alloc] initWithFrame:
CGRectMake(POTOIMGX, POTOIMGY, POTOIMGW, POTOIMGH)];
_icon.image = [UIImage imageNamed:@"biaoqingdi"];
[self.view addSubview:_icon];
}
return _icon;
}
/** 3. 描述標籤 */
- (UILabel *)lastlab {
if (!_lastlab) {
_lastlab = [[UILabel alloc] initWithFrame:CGRectMake(20, 400, 300, 30)];
[_lastlab setTextAlignment:NSTextAlignmentCenter];
[self.view addSubview:_lastlab];
}
return _lastlab;
}
/** 4. 左鍵 */
- (UIButton *)leftbtn {
if (!_leftbtn) {
_leftbtn = [UIButton buttonWithType:UIButtonTypeCustom];
_leftbtn.frame = CGRectMake(0, self.view.center.y, 40, 40);
[_leftbtn setBackgroundImage:[UIImage imageNamed:@"left_normal"]
forState:UIControlStateNormal];
[_leftbtn setBackgroundImage:[UIImage imageNamed:@"left_highlighted"]
forState:UIControlStateHighlighted];
[self.view addSubview:_leftbtn];
[_leftbtn addTarget:self action:@selector(leftclick:)
forControlEvents:UIControlEventTouchUpInside];
}
return _leftbtn;
}
/** 5. 右鍵 */
- (UIButton *)rightbtn {
if (!_rightbtn) {
_rightbtn = [UIButton buttonWithType:UIButtonTypeCustom];
_rightbtn.frame = CGRectMake(POTOIMGX + POTOIMGW + 10, self.view.center.y, 40, 40);
[_rightbtn setBackgroundImage:[UIImage imageNamed:@"right_normal"]
forState:UIControlStateNormal];
[_rightbtn setBackgroundImage:[UIImage imageNamed:@"right_highlighted"]
forState:UIControlStateHighlighted];
[self.view addSubview:_rightbtn];
[_rightbtn addTarget:self action:@selector(rightclick:)
forControlEvents:UIControlEventTouchUpInside];
}
return _rightbtn;
}
/** 資料來源也同樣延遲載入 */
- (NSArray *)array {
if (_array == nil) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
_array = [[NSArray alloc] initWithContentsOfFile:path];
}
return _array;
}
- (void)rightclick:(UIButton *)btn {
self.i++;
[self change];
}
- (void)leftclick:(UIButton *)btn {
self.i--;
[self change];
}
兩者都用來描述軟體界面,都由 Interface Builder 編輯。差別在粒度:
新增檔案並命名為 appxib.xib:


把 view 改為自由佈局,並設定好尺寸:


擺放內部控件並調整版面:


最直白的做法是用 viewWithTag: 從載入的視圖裡取出各控件:
@implementation YYViewController
// 1. 懶載入資料並轉模型
- (NSArray *)app {
if (!_app) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"app.plist" ofType:nil];
NSArray *temparray = [NSArray arrayWithContentsOfFile:path];
NSMutableArray *arrayM = [NSMutableArray array];
for (NSDictionary *dict in temparray) {
[arrayM addObject:[YYapp appWithDict:dict]];
}
_app = arrayM;
}
return _app;
}
// 2. 組出九宮格
- (void)viewDidLoad {
[super viewDidLoad];
int totalCol = 3;
CGFloat appViewW = 80;
CGFloat appViewH = 90;
CGFloat margin = (self.view.frame.size.width - totalCol * appViewW) / (totalCol + 1);
int count = self.app.count;
for (int i = 0; i < count; i++) {
int row = i / totalCol;
int loc = i % totalCol;
CGFloat appViewX = margin + (margin + appViewW) * loc;
CGFloat appViewY = margin + (margin + appViewH) * row;
YYapp *app = self.app[i];
// 從 xib 取出視圖
NSArray *appArray = [[NSBundle mainBundle] loadNibNamed:@"appxib" owner:nil options:nil];
UIView *appView = [appArray firstObject];
appView.frame = CGRectMake(appViewX, appViewY, appViewW, appViewH);
// 以 tag 取出內部控件並填資料
UIImageView *appViewImg = (UIImageView *)[appView viewWithTag:1];
appViewImg.image = app.image;
UILabel *appViewLab = (UILabel *)[appView viewWithTag:2];
appViewLab.text = app.name;
UIButton *appViewBtn = (UIButton *)[appView viewWithTag:3];
appViewBtn.tag = i;
[appViewBtn addTarget:self action:@selector(appviewbtnClick:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:appView];
}
}
- (void)appviewbtnClick:(UIButton *)btn {
YYapp *apps = self.app[btn.tag];
UILabel *showlab = [[UILabel alloc] initWithFrame:CGRectMake(60, 450, 200, 20)];
[showlab setText:[NSString stringWithFormat:@"%@下載成功", apps.name]];
[showlab setBackgroundColor:[UIColor lightGrayColor]];
[self.view addSubview:showlab];
showlab.alpha = 1.0;
[UIView animateWithDuration:2.0 animations:^{
showlab.alpha = 0;
} completion:^(BOOL finished) {
[showlab removeFromSuperview];
}];
}
@end

這種寫法有個明顯問題:控制器必須知道 xib 裡每個控件的 tag 值。它知道得太多,一旦 xib 改動,控制器就得跟著改。
做法是先建立一個繼承自 UIView 的類別,並在 xib 右上角把它關聯起來:


接著把各控件連線到這個類別:

注意:連線產生的屬性預設是 weak,實務上請改成 strong,否則視圖可能在還有引用時就被釋放。
對應的類別定義:
#import <UIKit/UIKit.h> @interface YYappview : UIView @property (strong, nonatomic) IBOutlet UIImageView *appimg; @property (strong, nonatomic) IBOutlet UILabel *applab; @property (strong, nonatomic) IBOutlet UIButton *appbtn; @end
控制器於是不再需要 tag,直接透過屬性操作,程式碼乾淨許多:
NSArray *appArray = [[NSBundle mainBundle] loadNibNamed:@"appxib" owner:nil options:nil];
// 注意此處的型別已改為 YYappview
YYappview *appView = [appArray firstObject];
appView.frame = CGRectMake(appViewX, appViewY, appViewW, appViewH);
[self.view addSubview:appView];
appView.appimg.image = app.image;
appView.applab.text = app.name;
appView.appbtn.tag = i;
[appView.appbtn addTarget:self action:@selector(appviewbtnClick:)
forControlEvents:UIControlEventTouchUpInside];