用 Storyboard 拉 cell 很直覺,但一旦版面需要精細控制、或專案有多個 target 要共用,純程式碼反而更好維護。以下三個檔案就是一個自訂 cell 的最小完整骨架。
#import <UIKit/UIKit.h>
@interface MyCell : UITableViewCell
@property (nonatomic, strong) UILabel *ageLabel;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *additionLabel;
- (instancetype)initWithStyle:(UITableViewCellStyle)style
reuseIdentifier:(NSString *)reuseIdentifier;
@end
#import "MyCell.h"
@implementation MyCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style
reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
_ageLabel = [[UILabel alloc] init];
_nameLabel = [[UILabel alloc] init];
_additionLabel = [[UILabel alloc] init];
_additionLabel.text = @"點擊";
// 全部掛到 contentView,而不是直接掛在 cell 上
[self.contentView addSubview:_ageLabel];
[self.contentView addSubview:_nameLabel];
[self.contentView addSubview:_additionLabel];
self.backgroundColor = [UIColor clearColor];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews]; // 不可省略:父類會在此調整分隔線位置
self.nameLabel.frame = CGRectMake(0, 0, 100, 44);
self.ageLabel.frame = CGRectMake(100, 0, 100, 44);
self.additionLabel.frame = CGRectMake(0, 40, 320, 20);
}
@end
init 執行時 cell 的 contentView.bounds 還沒定案,寫死座標看似可行,但一遇到不同螢幕尺寸、cell 被重用、或動態行高,frame 就會錯位。layoutSubviews 是系统在尺寸確定後呼叫的,這裡排版才是可靠的位置。
另外那行 [super layoutSubviews] 千万不能省——分隔線的位置調整是父類在這個方法裡做的,少了它就會出現分隔線不齊的問題。
#import "ViewController.h"
#import "MyCell.h"
@interface ViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) NSMutableArray *myData;
@end
@implementation ViewController
// 用懶載入準備資料;注意字典必須是可變的,否則後續改值會出問題
- (NSMutableArray *)myData {
if (!_myData) {
NSMutableDictionary *dict1 = [NSMutableDictionary
dictionaryWithObjects:@[@"hua", @12, @NO]
forKeys:@[@"name", @"age", @"flag"]];
NSMutableDictionary *dict2 = [NSMutableDictionary
dictionaryWithObjects:@[@"huhu", @14, @NO]
forKeys:@[@"name", @"age", @"flag"]];
NSMutableDictionary *dict3 = [NSMutableDictionary
dictionaryWithObjects:@[@"huxun", @16, @YES]
forKeys:@[@"name", @"age", @"flag"]];
_myData = [NSMutableArray arrayWithObjects:dict1, dict2, dict3, nil];
}
return _myData;
}
- (void)viewDidLoad {
[super viewDidLoad];
CGFloat customW = self.view.bounds.size.width;
CGFloat customH = self.view.bounds.size.height;
UITableView *tableview = [[UITableView alloc]
initWithFrame:CGRectMake(10, 44, customW - 2 * 10, customH - 80)
style:UITableViewStylePlain];
tableview.delegate = self;
tableview.dataSource = self;
tableview.separatorColor = [UIColor blueColor];
tableview.separatorInset = UIEdgeInsetsMake(0, 20, 0, 20);
self.myTableView = tableview;
[self.view addSubview:self.myTableView];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// 每一組有幾列
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.myData.count;
}
// 回傳自訂 cell,記得走重用機制
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ID = @"MyCell";
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (cell == nil) {
cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:ID];
}
// 在這裡把 myData[indexPath.row] 的值填進 cell 的三個 label
return cell;
}
// 依資料決定行高
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self.myData[indexPath.row][@"flag"] boolValue]) {
return 44 + 30;
}
return 44;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
cellForRowAtIndexPath: 只回傳空 cell。實務上要從 self.myData[indexPath.row] 取出字典,把 name、age 塞進對應 label;flag 則用來決定是否顯示 additionLabel。NSDictionary 建立,後續想改值會直接崩潰。但更根本的建議是:cell 的資料 model 應該用自訂的 model 類別(甚至用結構體),而不是 loose 的字典 key-value。cellLayoutMarginsFollowReadableWidth 與 iOS 13 的haviour 變更影響,邊緣裝置上可能不如預期。要精準控制分隔線,常見做法是自訂一條 0.5pt 的 view 放在 cell 底部。heightForRowAtIndexPath: 會被頻繁呼叫,裡面若要做文字量測,務必把結果快取,否則滾動會掉幀。cellForRowAtIndexPath: 裡明確重設,不能只設「有」不設「無」。