有時候我們需要自定義 UITableViewCell 的風格,本質上就是往行裡添加子視圖。添加方式主要有兩種:純程式碼,或從 xib 文件載入。後者比較直觀,本文以 xib 為主線來示範。
目標是左邊一張頭像,右邊三行標籤(暱稱、個性簽名、地區):

步驟 1:建立專案並把圖片資源導入。這裡準備了 14 張 50×50 的 png,命名為 1、2、……、14,放在 Images 資料夾中,拖進專案時勾選 Copy items 即可。



步驟 2:建立 UITableViewCell 的子類

輸入類名 CustomCell,Subclass of 選擇 UITableViewCell,就會產生 CustomCell.h 與 CustomCell.m。

步驟 3:建立 CustomCell.xib


步驟 4:在 xib 中布局
拖一個 Table View Cell 到面板上,選中它並在 Identity Inspector 中把 Class 設為 CustomCell,再到 Size Inspector 把高度調成 60。

接著往 Cell 裡放控件:左邊一個 50×50 的 ImageView,右邊三個 Label,最上面那個字號 14,其餘兩個 12。

然後建立 Outlet 連線,分別命名為 imageView、nameLabel、decLabel、locLable,對應頭像、暱稱、個性簽名與地區。
最後選中 Table View Cell,在 Attribute Inspector 中把 Identifier 設為 CustomCellIdentifier——這個值稍後註冊重用時必須一致。

步驟 5:在 CustomCell.h 中添加屬性
@property (copy, nonatomic) UIImage *image; @property (copy, nonatomic) NSString *name; @property (copy, nonatomic) NSString *dec; @property (copy, nonatomic) NSString *loc;
步驟 6:在 CustomCell.m 中重寫 setter
@synthesize image;
@synthesize name;
@synthesize dec;
@synthesize loc;
- (void)setImage:(UIImage *)img {
if (![img isEqual:image]) {
image = [img copy];
self.imageView.image = image;
}
}
- (void)setName:(NSString *)n {
if (![n isEqualToString:name]) {
name = [n copy];
self.nameLabel.text = name;
}
}
- (void)setDec:(NSString *)d {
if (![d isEqualToString:dec]) {
dec = [d copy];
self.decLabel.text = dec;
}
}
- (void)setLoc:(NSString *)l {
if (![l isEqualToString:loc]) {
loc = [l copy];
self.locLabel.text = loc;
}
}
這樣做相當於重寫了各個 setter,於是外部只要賦值,界面就會同步更新,呼叫端的程式碼非常乾淨。
步驟 7:準備資料
建立一個 friendsInfo.plist 存放顯示資料,注意每個節點的類型要選對。

步驟 8:在檢視控制器中使用
把 Table View 拖到 ViewController.xib 上,並將 Delegate 與 DataSource 都指向 File's Owner。
#import <UIKit/UIKit.h> @interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> @property (strong, nonatomic) NSArray *dataList; @property (strong, nonatomic) NSArray *imageList; @end
#import "CustomCell.h"
@implementation ViewController
@synthesize dataList;
@synthesize imageList;
- (void)viewDidLoad {
[super viewDidLoad];
// 載入 plist 中的資料與圖片
NSBundle *bundle = [NSBundle mainBundle];
NSURL *plistURL = [bundle URLForResource:@"friendsInfo" withExtension:@"plist"];
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:plistURL];
NSMutableArray *tmpDataArray = [[NSMutableArray alloc] init];
NSMutableArray *tmpImageArray = [[NSMutableArray alloc] init];
for (int i = 0; i < dictionary.count; i++) {
NSString *key = [[NSString alloc] initWithFormat:@"%i", i + 1];
[tmpDataArray addObject:[dictionary objectForKey:key]];
NSString *imageUrl = [[NSString alloc] initWithFormat:@"%i.png", i + 1];
[tmpImageArray addObject:[UIImage imageNamed:imageUrl]];
}
self.dataList = [tmpDataArray copy];
self.imageList = [tmpImageArray copy];
}
- (void)viewDidUnload {
self.dataList = nil;
self.imageList = nil;
}
#pragma mark - Table Data Source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.dataList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CustomCellIdentifier = @"CustomCellIdentifier";
// 只註冊一次即可
static BOOL nibsRegistered = NO;
if (!nibsRegistered) {
UINib *nib = [UINib nibWithNibName:@"CustomCell" bundle:nil];
[tableView registerNib:nib forCellReuseIdentifier:CustomCellIdentifier];
nibsRegistered = YES;
}
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
NSUInteger row = [indexPath row];
NSDictionary *rowData = [self.dataList objectAtIndex:row];
cell.name = [rowData objectForKey:@"name"];
cell.dec = [rowData objectForKey:@"dec"];
cell.loc = [rowData objectForKey:@"loc"];
cell.image = [self.imageList objectAtIndex:row];
return cell;
}
#pragma mark - Table Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 60.0;
}
// 不允許選中
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
return nil;
}

重用的目的是降低記憶體消耗。假如有一千個 cell,若完全不重用,每次滑動都要重新 alloc 大量物件,不僅耗記憶體,畫面還會因為來不及建立而出現斷續、閃動的現象。
重用的寫法很簡單:用 initWithStyle:reuseIdentifier: 建立實例,而不是 initWithFrame:;identifier 用一個固定的字串即可。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
// 先嘗試從重用佇列取出
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
// 佇列中沒有可重用的 cell,才建立新的實例
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
} else {
NSLog(@"cell 重用啦");
}
return cell;
}
這件事必須靠下面這個方法:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
實務上常見的做法是:在建立或重用 cell 時設定它的 frame,例如 cell.frame = CGRectMake(0, 0, 320, 450);,然後在 heightForRowAtIndexPath: 中取用這個高度:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *myCell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
if (myCell == nil) {
return 0;
}
return myCell.frame.size.height;
}
不過要留意:這種寫法會讓同一個 indexPath 的 cell 被多建立一次實例,等於每個 cell 實際上有兩個物件。更好的做法是在建立 cell 時就把計算好的高度存進一個私有陣列,在 heightForRowAtIndexPath: 中直接讀取,既避免重複建立,效能也更佳。
先設定字型,再用 boundingRectWithSize: 算出實際佔用的矩形:
tmLabel.font = [UIFont systemFontOfSize:14.0f];
NSDictionary *attrDic = @{NSFontAttributeName : [UIFont systemFontOfSize:12.0f]};
CGSize labelSize = [text boundingRectWithSize:CGSizeMake(320, 990)
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:attrDic
context:nil].size;
CGRect labelRect = CGRectMake(0, 0, labelSize.width, labelSize.height);
如果 cell 裡還有其他控件(例如 UIButton),做法完全一樣:實例化時 frame 先給 CGRectZero,各自算出尺寸後再依序累加,並用 cell.contentView addSubview: 加入。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.tag = 1;
label.lineBreakMode = NSLineBreakByCharWrapping;
label.numberOfLines = 0;
label.opaque = NO;
label.font = [UIFont systemFontOfSize:12.0f];
label.backgroundColor = [UIColor grayColor];
[cell.contentView addSubview:label];
UIButton *tmpButton = [[UIButton alloc] initWithFrame:CGRectZero];
tmpButton.tag = 2;
tmpButton.backgroundColor = [UIColor cyanColor];
tmpButton.opaque = NO;
[tmpButton setTitle:@"nihao" forState:UIControlStateNormal];
[tmpButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[tmpButton addTarget:self action:@selector(tmpButtonHandler:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:tmpButton];
} else {
NSLog(@"cell 重用啦");
}
UILabel *tmpLabel = (UILabel *)[cell viewWithTag:1];
NSString *text = [tmpArray objectAtIndex:indexPath.row];
tmpLabel.text = text;
UIButton *tmpButton = (UIButton *)[cell viewWithTag:2];
// 計算 label 尺寸
NSDictionary *attrDic = @{NSFontAttributeName : [UIFont systemFontOfSize:12.0f]};
CGSize labelSize = [text boundingRectWithSize:CGSizeMake(320, 990)
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:attrDic
context:nil].size;
CGRect labelRect = CGRectMake(0, 0, labelSize.width, labelSize.height);
[tmpLabel setFrame:labelRect];
// 按鈕接在 label 下方
[tmpButton setFrame:CGRectMake(0, labelSize.height + 1, 100, 50)];
// cell 高度 = 兩個子控件高度之和
[cell setFrame:CGRectMake(0, 0, labelSize.width, labelSize.height + 50 + 1)];
return cell;
}
為什麼 frame 的設定要放在 if/else 之後,而不是放在建立 cell 的分支裡?因為重用時從佇列取出的 cell 裡裝的是前一次的內容,必須重新填充文字並重新計算高度;而建立新 cell 時也需要設定一次。兩條邏輯完全相同,因此直接移到 if/else 之外統一執行,避免重複程式碼。