

模型:
// YYtg.h #import <Foundation/Foundation.h> #import "Global.h" @interface YYtg : NSObject @property (nonatomic, copy) NSString *buyCount; @property (nonatomic, copy) NSString *icon; @property (nonatomic, copy) NSString *price; @property (nonatomic, copy) NSString *title; YYinitH(tg) @end // YYtg.m #import "YYtg.h" @implementation YYtg YYinitM(tg) @end
控制器:
#import "YYViewController.h"
#import "YYtg.h"
@interface YYViewController () <UITableViewDataSource>
@property (nonatomic, strong) NSArray *tg;
@property (strong, nonatomic) IBOutlet UITableView *tableview;
@end
@implementation YYViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableview.rowHeight = 100;
}
#pragma mark - 懶加載
- (NSArray *)tg {
if (_tg == nil) {
NSString *fullpath = [[NSBundle mainBundle] pathForResource:@"tgs.plist" ofType:nil];
NSArray *temparray = [NSArray arrayWithContentsOfFile:fullpath];
NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:temparray.count];
for (NSDictionary *dict in temparray) {
YYtg *tg = [YYtg tgWithDict:dict];
[arrayM addObject:tg];
}
_tg = [arrayM mutableCopy];
}
return _tg;
}
#pragma mark - 資料顯示
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.tg.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"tg";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
// 從 xib 載入
cell = [[[NSBundle mainBundle] loadNibNamed:@"tgcell" owner:nil options:nil] firstObject];
}
YYtg *tg = self.tg[indexPath.row];
// 用 tag 逐一填值
UIImageView *imgv = (UIImageView *)[cell viewWithTag:1];
imgv.image = [UIImage imageNamed:tg.icon];
UILabel *title = (UILabel *)[cell viewWithTag:2];
title.text = tg.title;
UILabel *price = (UILabel *)[cell viewWithTag:3];
price.text = [NSString stringWithFormat:@"$%@", tg.price];
UILabel *buyCount = (UILabel *)[cell viewWithTag:4];
buyCount.text = [NSString stringWithFormat:@"已有%@人購買", tg.buyCount];
return cell;
}
- (BOOL)prefersStatusBarHidden {
return YES;
}
@end

這樣寫的問題:控制器必須知道 xib 中所有控件的 tag。一個主控制器把底層細節知道得這麼清楚,本身就是設計上的警訊。解法是替 cell 配一個專屬類別,讓它自己去操作 xib,對外只暴露模型屬性。
建立類別時別忘了把父類別設為 UITableViewCell,並與 xib 正確關聯:

// YYtgcell.h
#import <UIKit/UIKit.h>
#import "YYtg.h"
@interface YYtgcell : UITableViewCell
@property (nonatomic, strong) YYtg *yytg;
@end
// YYtgcell.m
#import "YYtgcell.h"
// 私有擴展:內部控件不外露
@interface YYtgcell()
@property (strong, nonatomic) IBOutlet UIImageView *img;
@property (strong, nonatomic) IBOutlet UILabel *titlelab;
@property (strong, nonatomic) IBOutlet UILabel *pricelab;
@property (strong, nonatomic) IBOutlet UILabel *buycountlab;
@end
@implementation YYtgcell
// 覆寫 setter,把「模型 → 畫面」的對應關係收在 cell 內部
- (void)setYytg:(YYtg *)yytg {
_yytg = yytg;
self.img.image = [UIImage imageNamed:yytg.icon];
self.titlelab.text = yytg.title;
self.pricelab.text = [NSString stringWithFormat:@"$%@", yytg.price];
self.buycountlab.text = [NSString stringWithFormat:@"已有%@人購買", yytg.buyCount];
}
@end
控制器這邊只剩下一行賦值:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"tg";
YYtgcell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[[NSBundle mainBundle] loadNibNamed:@"tgcell" owner:nil options:nil] firstObject];
}
cell.yytg = self.tg[indexPath.row];
return cell;
}
再往前一步,連 dequeue 與 xib 載入的細節都收進 cell 類別,對外提供一個便利建構子:
// YYtgcell.h
+ (instancetype)tgcellWithTableView:(UITableView *)tableView;
// YYtgcell.m
+ (instancetype)tgcellWithTableView:(UITableView *)tableView {
static NSString *identifier = @"tg";
YYtgcell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
// 對 xib 而言,重用識別碼可直接在屬性檢視器中設定
cell = [[[NSBundle mainBundle] loadNibNamed:@"tgcell" owner:nil options:nil] firstObject];
}
return cell;
}
於是 cellForRowAtIndexPath: 變得非常清爽,這也更貼近 MVC 的分層意圖:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// 1. 建立 cell
YYtgcell *cell = [YYtgcell tgcellWithTableView:tableView];
// 2. 取值並設定資料
cell.yytg = self.tg[indexPath.row];
// 3. 回傳
return cell;
}
建議的檔案結構(完整的 MVC 分層):

另外別忽略命名規範。Xcode 支援批次改名:



UITableViewCell 的類別。initWithStyle:reuseIdentifier::在此加入所有要顯示的子控件(只加入,不設定資料與 frame,且要加到 contentView 上),並完成一次性的屬性設定(字體、固定圖片等)。這樣設計的理由很實際:frame 計算(尤其是文字尺寸測量)成本不低,若放在 cellForRowAtIndexPath: 或 layoutSubviews 中,滾動時會反覆觸發而掉幀。抽到 frame 模型並快取,就只算一次。

// NJWeibo.h
@interface NJWeibo : NSObject
@property (nonatomic, copy) NSString *text; // 內容
@property (nonatomic, copy) NSString *icon; // 頭像
@property (nonatomic, copy) NSString *name; // 暱稱
@property (nonatomic, copy) NSString *picture; // 配圖
@property (nonatomic, assign) BOOL vip;
- (id)initWithDict:(NSDictionary *)dict;
+ (id)weiboWithDict:(NSDictionary *)dict;
@end
// NJWeibo.m
@implementation NJWeibo
- (id)initWithDict:(NSDictionary *)dict {
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
+ (id)weiboWithDict:(NSDictionary *)dict {
return [[self alloc] initWithDict:dict];
}
@end
// NJWeiboCell.h
#import <UIKit/UIKit.h>
@class NJWeiboFrame;
@interface NJWeiboCell : UITableViewCell
@property (nonatomic, strong) NJWeiboFrame *weiboFrame;
+ (instancetype)cellWithTableView:(UITableView *)tableView;
@end
// NJWeiboCell.m
#import "NJWeiboCell.h"
#import "NJWeibo.h"
#import "NJWeiboFrame.h"
#define NJNameFont [UIFont systemFontOfSize:15]
#define NJTextFont [UIFont systemFontOfSize:16]
@interface NJWeiboCell ()
@property (nonatomic, weak) UIImageView *iconView; // 頭像
@property (nonatomic, weak) UIImageView *vipView; // VIP 標記
@property (nonatomic, weak) UIImageView *pictureView; // 配圖
@property (nonatomic, weak) UILabel *nameLabel; // 暱稱
@property (nonatomic, weak) UILabel *introLabel; // 正文
@end
@implementation NJWeiboCell
+ (instancetype)cellWithTableView:(UITableView *)tableView {
static NSString *identifier = @"status";
// 1. 先從重用池取
NJWeiboCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
// 2. 沒有才建立
if (cell == nil) {
cell = [[NJWeiboCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:identifier];
}
return cell;
}
/**
* 建構方法:只負責「建立並加入子控件」與「一次性屬性設定」,
* 不在此處設定資料與 frame。
*/
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// 1. 頭像
UIImageView *iconView = [[UIImageView alloc] init];
[self.contentView addSubview:iconView];
self.iconView = iconView;
// 2. 暱稱
UILabel *nameLabel = [[UILabel alloc] init];
nameLabel.font = NJNameFont;
[self.contentView addSubview:nameLabel];
self.nameLabel = nameLabel;
// 3. VIP 標記
UIImageView *vipView = [[UIImageView alloc] init];
vipView.image = [UIImage imageNamed:@"vip"];
[self.contentView addSubview:vipView];
self.vipView = vipView;
// 4. 正文(行數不限)
UILabel *introLabel = [[UILabel alloc] init];
introLabel.font = NJTextFont;
introLabel.numberOfLines = 0;
[self.contentView addSubview:introLabel];
self.introLabel = introLabel;
// 5. 配圖
UIImageView *pictureView = [[UIImageView alloc] init];
[self.contentView addSubview:pictureView];
self.pictureView = pictureView;
}
return self;
}
// frame 模型一設定,就同步資料與版面
- (void)setWeiboFrame:(NJWeiboFrame *)weiboFrame {
_weiboFrame = weiboFrame;
[self settingData];
[self settingFrame];
}
- (void)settingData {
NJWeibo *weibo = self.weiboFrame.weibo;
self.iconView.image = [UIImage imageNamed:weibo.icon];
self.nameLabel.text = weibo.name;
if (weibo.vip) {
self.vipView.hidden = NO;
self.nameLabel.textColor = [UIColor redColor];
} else {
self.vipView.hidden = YES;
self.nameLabel.textColor = [UIColor blackColor];
}
self.introLabel.text = weibo.text;
// 沒有配圖就隱藏
if (weibo.picture) {
self.pictureView.image = [UIImage imageNamed:weibo.picture];
self.pictureView.hidden = NO;
} else {
self.pictureView.hidden = YES;
}
}
- (void)settingFrame {
self.iconView.frame = self.weiboFrame.iconF;
self.nameLabel.frame = self.weiboFrame.nameF;
self.vipView.frame = self.weiboFrame.vipF;
self.introLabel.frame = self.weiboFrame.introF;
if (self.weiboFrame.weibo.picture) {
self.pictureView.frame = self.weiboFrame.pictrueF;
}
}
@end
// NJWeiboFrame.h
#import <Foundation/Foundation.h>
@class NJWeibo;
@interface NJWeiboFrame : NSObject
@property (nonatomic, assign) CGRect iconF; // 頭像
@property (nonatomic, assign) CGRect nameF; // 暱稱
@property (nonatomic, assign) CGRect vipF; // VIP
@property (nonatomic, assign) CGRect introF; // 正文
@property (nonatomic, assign) CGRect pictrueF; // 配圖
@property (nonatomic, assign) CGFloat cellHeight;
@property (nonatomic, strong) NJWeibo *weibo;
@end
// NJWeiboFrame.m
#import "NJWeiboFrame.h"
#import "NJWeibo.h"
#define NJNameFont [UIFont systemFontOfSize:15]
#define NJTextFont [UIFont systemFontOfSize:16]
@implementation NJWeiboFrame
- (void)setWeibo:(NJWeibo *)weibo {
_weibo = weibo;
CGFloat padding = 10; // 間距
// 頭像
CGFloat iconViewX = padding;
CGFloat iconViewY = padding;
CGFloat iconViewW = 30;
CGFloat iconViewH = 30;
self.iconF = CGRectMake(iconViewX, iconViewY, iconViewW, iconViewH);
// 暱稱:x 為頭像右緣 + 間距,y 與頭像垂直居中含有對齊
CGFloat nameLabelX = CGRectGetMaxX(self.iconF) + padding;
CGSize nameSize = [self sizeWithString:_weibo.name
font:NJNameFont
maxSize:CGSizeMake(MAXFLOAT, MAXFLOAT)];
CGFloat nameLabelH = nameSize.height;
CGFloat nameLabelW = nameSize.width;
CGFloat nameLabelY = iconViewY + (iconViewH - nameLabelH) * 0.5;
self.nameF = CGRectMake(nameLabelX, nameLabelY, nameLabelW, nameLabelH);
// VIP:接在暱稱右側
CGFloat vipViewX = CGRectGetMaxX(self.nameF) + padding;
CGFloat vipViewY = nameLabelY;
self.vipF = CGRectMake(vipViewX, vipViewY, 14, 14);
// 正文:寬度上限 300,高度則依內容自動撐開
CGFloat introLabelX = iconViewX;
CGFloat introLabelY = CGRectGetMaxY(self.iconF) + padding;
CGSize textSize = [self sizeWithString:_weibo.text
font:NJTextFont
maxSize:CGSizeMake(300, MAXFLOAT)];
self.introF = CGRectMake(introLabelX, introLabelY, textSize.width, textSize.height);
// 配圖與行高:有無配圖會影響 cell 高度
if (_weibo.picture) {
CGFloat pictureViewX = iconViewX;
CGFloat pictureViewY = CGRectGetMaxY(self.introF) + padding;
self.pictrueF = CGRectMake(pictureViewX, pictureViewY, 100, 100);
self.cellHeight = CGRectGetMaxY(self.pictrueF) + padding;
} else {
self.cellHeight = CGRectGetMaxY(self.introF) + padding;
}
}
/**
* 計算文字實際佔用的尺寸。
* 若內容超出 maxSize 則回傳 maxSize,否則回傳真實尺寸。
*/
- (CGSize)sizeWithString:(NSString *)str font:(UIFont *)font maxSize:(CGSize)maxSize {
NSDictionary *dict = @{NSFontAttributeName : font};
return [str boundingRectWithSize:maxSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:dict
context:nil].size;
}
@end
#import "NJViewController.h"
#import "NJWeibo.h"
#import "NJWeiboCell.h"
#import "NJWeiboFrame.h"
@interface NJViewController ()
@property (nonatomic, strong) NSArray *statusFrames;
@end
@implementation NJViewController
#pragma mark - 資料來源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.statusFrames.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NJWeiboCell *cell = [NJWeiboCell cellWithTableView:tableView];
cell.weiboFrame = self.statusFrames[indexPath.row];
return cell;
}
#pragma mark - 懶加載:一次把資料模型轉成 frame 模型
- (NSArray *)statusFrames {
if (_statusFrames == nil) {
NSString *fullPath = [[NSBundle mainBundle] pathForResource:@"statuses.plist" ofType:nil];
NSArray *dictArray = [NSArray arrayWithContentsOfFile:fullPath];
NSMutableArray *models = [NSMutableArray arrayWithCapacity:dictArray.count];
for (NSDictionary *dict in dictArray) {
NJWeibo *weibo = [NJWeibo weiboWithDict:dict];
NJWeiboFrame *wbF = [[NJWeiboFrame alloc] init];
wbF.weibo = weibo; // 設定模型的同時即完成 frame 計算
[models addObject:wbF];
}
self.statusFrames = [models copy];
}
return _statusFrames;
}
#pragma mark - 代理方法:直接讀快取好的行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NJWeiboFrame *wbF = self.statusFrames[indexPath.row];
return wbF.cellHeight;
}
- (BOOL)prefersStatusBarHidden {
return YES;
}
@end
系統預設的 cell 未必能滿足設計需求,因此自訂是常態。兩種做法各有適用時機: