本文以微博列表為例,說明如何不依賴 Storyboard 的 cell 設計,改用純程式碼建立自訂 UITableViewCell。整體流程可分為:準備資料、建立模型、建立 cell、設定資料源。
將 plist 與圖片資源加入專案,透過 NSBundle 讀取 statuses.plist,再把字典轉成模型。若屬性包含 bool 型別,KVC 通常能將 NSNumber 轉為 BOOL。
@interface YYweiboModel : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *text;
@property (nonatomic, copy) NSString *icon;
@property (nonatomic, copy) NSString *picture;
@property (nonatomic, assign) BOOL vip;
- (instancetype)initWithDict:(NSDictionary *)dict;
+ (instancetype)weiboModelWithDict:(NSDictionary *)dict;
@end
實作時可用 setValuesForKeysWithDictionary: 快速完成 KVC 賦值,再提供 factory method 方便建立物件。
自訂 cell 繼承 UITableViewCell,在 initWithStyle:reuseIdentifier: 中建立頭像、暱稱、VIP 圖示、正文與配圖,並加入 contentView。外部傳入模型時,於 setWeibo: 中更新子控件的 image、text 與 frame。
- (void)setWeibo:(YYweiboModel *)weibo {
_weibo = weibo;
self.iconView.image = [UIImage imageNamed:weibo.icon];
self.nameLabel.text = weibo.name;
self.textLab.text = weibo.text;
self.pictureView.image = [UIImage imageNamed:weibo.picture];
[self settingFrame];
}
在 UITableViewController 中實作 numberOfRowsInSection: 與 cellForRowAtIndexPath:。先從 reuse queue 取得 cell,若無則建立,再將模型指派給 cell。如此可維持 delegate/data source 與 view 的低耦合。