完成一個三列的應用圖示列表:

九宮格的關鍵只有兩條公式:用索引除以欄數得到「第幾列」,用索引除以欄數取餘數得到「第幾行」。

#import "YYViewController.h"
@interface YYViewController ()
@property (nonatomic, strong) NSArray *apps;
@end
@implementation YYViewController
// 1. 懶載入資料
- (NSArray *)apps {
if (!_apps) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"app.plist" ofType:nil];
_apps = [NSArray arrayWithContentsOfFile:path];
}
return _apps;
}
- (void)viewDidLoad {
[super viewDidLoad];
// 2. 版面參數
int totalCol = 3; // 三列
CGFloat appViewW = 80;
CGFloat appViewH = 90;
// 左右(與間距)邊距由剩餘寬度平均分配
CGFloat margin = (self.view.frame.size.width - totalCol * appViewW) / (totalCol + 1);
int count = self.apps.count;
for (int i = 0; i < count; i++) {
int row = i / totalCol; // 第幾列:1/3=0, 2/3=0, 3/3=1
int loc = i % totalCol; // 第幾行:0,1,2,0,1,2...
CGFloat appViewX = margin + (margin + appViewW) * loc;
CGFloat appViewY = margin + (margin + appViewH) * row;
// 建立格子容器
UIView *appView = [[UIView alloc] initWithFrame:
CGRectMake(appViewX, appViewY, appViewW, appViewH)];
[self.view addSubview:appView];
// 圖示
UIImageView *appImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 80, 50)];
appImageView.image = [UIImage imageNamed:self.apps[i][@"icon"]];
appImageView.contentMode = UIViewContentModeScaleAspectFit;
[appView addSubview:appImageView];
// 名稱
UILabel *appLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, 80, 20)];
appLabel.text = self.apps[i][@"name"];
appLabel.textAlignment = NSTextAlignmentCenter;
appLabel.font = [UIFont systemFontOfSize:12.0];
[appView addSubview:appLabel];
// 按鈕
UIButton *appBtn = [UIButton buttonWithType:UIButtonTypeCustom];
appBtn.frame = CGRectMake(10, 70, 60, 20);
[appBtn setBackgroundImage:[UIImage imageNamed:@"buttongreen"]
forState:UIControlStateNormal];
[appBtn setBackgroundImage:[UIImage imageNamed:@"buttongreen_highlighted"]
forState:UIControlStateHighlighted];
[appBtn setTitle:@"下載" forState:UIControlStateNormal];
appBtn.titleLabel.font = [UIFont systemFontOfSize:12.0];
[appView addSubview:appBtn];
[appBtn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
}
}
// 點擊後顯示提示並淡出
- (void)click {
UILabel *animLabel = [[UILabel alloc]
initWithFrame:CGRectMake(self.view.center.x - 100, self.view.center.y + 20, 200, 40)];
animLabel.text = @"下載成功";
animLabel.font = [UIFont systemFontOfSize:12.0];
animLabel.backgroundColor = [UIColor brownColor];
animLabel.alpha = 0;
[self.view addSubview:animLabel];
// 建議直接用 block 動畫,比 begin/commit 首尾式動畫簡潔,也方便處理完成後的收尾
[UIView animateWithDuration:4.0 animations:^{
animLabel.alpha = 1;
} completion:^(BOOL finished) {
// 可在此移除 animLabel
}];
}
@end

資料來源是這樣的 plist:

直白的寫法是在控制器裡到處寫 dict[@"icon"]、dict[@"name"]:
@implementation LFViewController
- (NSArray *)appList {
if (!_appList) {
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:@"app.plist" ofType:nil];
_appList = [NSArray arrayWithContentsOfFile:path];
}
return _appList;
}
- (void)viewDidLoad {
[super viewDidLoad];
int totalCol = 3;
CGFloat viewW = 80;
CGFloat viewH = 90;
CGFloat marginX = (self.view.bounds.size.width - totalCol * viewW) / (totalCol + 1);
CGFloat marginY = 10;
CGFloat startY = 20;
for (int i = 0; i < self.appList.count; i++) {
int row = i / totalCol;
int col = i % totalCol;
CGFloat x = marginX + (viewW + marginX) * col;
CGFloat y = startY + marginY + (viewH + marginY) * row;
UIView *appView = [[UIView alloc] initWithFrame:CGRectMake(x, y, viewW, viewH)];
[self.view addSubview:appView];
NSDictionary *dict = self.appList[i];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, viewW, 50)];
imageView.image = [UIImage imageNamed:dict[@"icon"]];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[appView addSubview:imageView];
UILabel *label = [[UILabel alloc]
initWithFrame:CGRectMake(0, imageView.bounds.size.height, viewW, 20)];
label.text = dict[@"name"];
label.font = [UIFont systemFontOfSize:12.0];
label.textAlignment = NSTextAlignmentCenter;
[appView addSubview:label];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(15, 70, viewW - 30, 20);
// 注意:不能直接用 button.titleLabel.text 設定標題
[button setTitle:@"下載" forState:UIControlStateNormal];
button.titleLabel.font = [UIFont systemFontOfSize:14.0];
[button setBackgroundImage:[UIImage imageNamed:@"buttongreen"]
forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"buttongreen_highlighted"]
forState:UIControlStateHighlighted];
[appView addSubview:button];
}
}
@end

問題在哪?控制器直接依賴字串 key。key 是手打的、沒有智能提示,一旦打錯,編譯器不會有任何警告,只會安靜地存進錯誤的資料或取出 nil。這類問題在專案變大後極難排查。

好處:
模型應提供可傳入字典的建構方法:
- (instancetype)initWithDict:(NSDictionary *)dict; + (instancetype)xxxWithDict:(NSDictionary *)dict;
若再加上合理的 readonly 屬性,耦合度還能再降一層。
模型標頭:
#import <Foundation/Foundation.h> @interface LFAppInfo : NSObject // 應用程式名稱 @property (nonatomic, copy) NSString *name; // 應用程式圖示名稱 @property (nonatomic, copy) NSString *icon; // 圖像(readonly 只會產生 getter,不會產生帶底線的成員變數) @property (nonatomic, strong, readonly) UIImage *image; // instancetype 會讓編譯器檢查實例化結果的型別, // 且只能作為回傳型別,不能當參數使用 - (instancetype)initWithDict:(NSDictionary *)dict; /** 工廠方法 */ + (instancetype)appInfoWithDict:(NSDictionary *)dict; @end
模型實作。image 做成延遲計算的快取值,避免重複解圖:
#import "LFAppInfo.h"
@interface LFAppInfo()
{
UIImage *_imageABC;
}
@end
@implementation LFAppInfo
- (instancetype)initWithDict:(NSDictionary *)dict {
self = [super init];
if (self) {
self.name = dict[@"name"];
self.icon = dict[@"icon"];
}
return self;
}
+ (instancetype)appInfoWithDict:(NSDictionary *)dict {
return [[self alloc] initWithDict:dict];
}
- (UIImage *)image {
if (!_imageABC) {
_imageABC = [UIImage imageNamed:self.icon];
}
return _imageABC;
}
@end
控制器這邊只負責「把陣列裡的字典換成模型」:
- (NSArray *)appList {
if (!_appList) {
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:@"app.plist" ofType:nil];
NSArray *array = [NSArray arrayWithContentsOfFile:path];
// 遍歷陣列,逐筆轉成模型後放進暫存陣列
NSMutableArray *arrayM = [NSMutableArray array];
for (NSDictionary *dict in array) {
[arrayM addObject:[LFAppInfo appInfoWithDict:dict]];
}
_appList = arrayM;
}
return _appList;
}
之後取資料就完全走屬性,不再有意外的字串 key:
LFAppInfo *appInfo = self.appList[i]; imageView.image = appInfo.image; label.text = appInfo.name;
按鈕的部分則用 tag 記住索引,點擊時回頭取對應模型:
button.tag = i;
[button addTarget:self action:@selector(downloadClick:) forControlEvents:UIControlEventTouchUpInside];
- (void)downloadClick:(UIButton *)button {
LFAppInfo *appInfo = self.appList[button.tag];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(80, 400, 160, 40)];
label.textAlignment = NSTextAlignmentCenter;
label.backgroundColor = [UIColor lightGrayColor];
label.text = [NSString stringWithFormat:@"下載%@完成", appInfo.name];
label.font = [UIFont systemFontOfSize:13.0];
label.alpha = 1.0;
[self.view addSubview:label];
// block 動畫比首尾式動畫簡潔,且能直接處理結束後的收尾
[UIView animateWithDuration:2.0 animations:^{
label.alpha = 0.0;
} completion:^(BOOL finished) {
[label removeFromSuperview];
}];
}
plist 的讀取其實也屬於模型的職責,因此可以把 +questions 這類「直接回傳模型陣列」的類方法放進模型:
// LFQuestion.h
@interface LFQuestion : NSObject
@property (nonatomic, copy) NSString *answer;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *icon;
@property (nonatomic, strong) NSArray *options;
@property (nonatomic, strong) UIImage *image;
- (instancetype)initWithDict:(NSDictionary *)dict;
+ (instancetype)questionWithDict:(NSDictionary *)dict;
/** 從 plist 直接載入物件陣列 */
+ (NSArray *)questions;
@end
// LFQuestion.m
+ (NSArray *)questions {
NSArray *array = [NSArray arrayWithContentsOfFile:
[[NSBundle mainBundle] pathForResource:@"questions.plist" ofType:nil]];
NSMutableArray *arrayM = [NSMutableArray array];
for (NSDictionary *dict in array) {
[arrayM addObject:[LFQuestion questionWithDict:dict]];
}
return arrayM;
}
控制器於是瘦成一行:
- (NSArray *)questions {
if (!_questions) {
_questions = [LFQuestion questions];
}
return _questions;
}
逐行 self.xxx = dict[@"xxx"] 可以用鍵值編碼取代:
- (instancetype)initWithDict:(NSDictionary *)dict {
self = [super init];
if (self) {
// KVC(Key Value Coding)是 Cocoa 的一項核心能力,
// 允許以間接方式設定物件屬性
[self setValue:dict[@"answer"] forKeyPath:@"answer"];
[self setValue:dict[@"icon"] forKeyPath:@"icon"];
[self setValue:dict[@"title"] forKeyPath:@"title"];
[self setValue:dict[@"options"] forKeyPath:@"options"];
}
return self;
}
更乾脆的做法是 setValuesForKeysWithDictionary::
- (instancetype)initWithDict:(NSDictionary *)dict {
self = [super init];
if (self) {
// 使用時機制的限制:模型的屬性必須在字典中都存在,
// 屬性數量可以比字典的 key 多,但不能少
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
id,它多了一層編譯器型的檢查。