做過列表頁的同學大概都遇過這類尷尬:系統自帶的分隔線左邊空出一大截,看起來像沒畫完;設計稿又常常要求線條通欄到底,或者換個顏色、改個粗細。這篇文章把常見場景整理成兩套可直接複用的做法。
從 iOS 8 開始,UITableView 的分割線會跟著 cell 的 layoutMargins 走,而 cell 的 layoutMargins 又受 separatorInset 影響。所以想讓線條貼齊左右邊緣,關鍵是把這兩個值都歸零,而且三個地方都要照顧到:tableView 本身、即將出現的 cell、以及 cell 內部重新布局的時機。
TableView.separatorStyle = UITableViewCellEditingStyleSingleLine; // 保留系統預設樣式
- (void)viewDidLayoutSubviews {
if ([TableView respondsToSelector:@selector(setSeparatorInset:)]) {
[TableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([TableView respondsToSelector:@selector(setLayoutMargins:)]) {
[TableView setLayoutMargins:UIEdgeInsetsZero];
}
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
[cell setSeparatorInset:UIEdgeInsetsZero];
}
}
為什麼要寫在 viewDidLayoutSubviews 裡?因為 cell 在復用和旋轉時會重新計算內邊距,只在初始化時設置一次,滾動幾屏之後往往又被系統覆蓋回去了。
如果需求是「只要底部一條線」「線要短一截」「顏色得跟品牌色一致」,那與其跟系統的 inset 機制纏鬥,不如直接關掉它,用 Core Graphics 自己畫。
TableView.separatorStyle = UITableViewCellEditingStyleNone; // 丟掉系統線
#define SINGLE_LINE_HEIGHT (1.0 / [UIScreen mainScreen].scale) // 1 物理像素
#define COLOR_LINE_GRAY [UIColor colorWithRed:224/255.0 green:224/255.0 blue:224/255.0 alpha:1.0]
// 在自定義 cell 中重寫
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
CGContextFillRect(context, rect);
// 底部分隔線
CGContextSetStrokeColorWithColor(context, COLOR_LINE_GRAY.CGColor);
CGContextStrokeRect(context, CGRectMake(0, rect.size.height, rect.size.width, SINGLE_LINE_HEIGHT));
}
兩個實用小細節:
1.0 / scale 而不是 0.5,是為了在 2x、3x 螢幕上都剛好對齊一個物理像素,線條才不會發虛發灰。UIView(高度設為 SINGLE_LINE_HEIGHT),或者用 layer 的邊框屬性,性能與可維護性通常比重寫 drawRect: 更好。drawRect: 的優勢在於位置可以精確到任意像素,適合線條需要避開圓角、避開自定義按鈕這類複雜排版。通欄需求優先調 separatorInset 與 layoutMargins;其餘任何「不像系統樣子」的需求,直接關掉 separatorStyle 自己畫,反而更可控。