建立 tableView 時仔細看會發現,cell 的分割線左側有一小段空白,並沒有貫穿整個螢幕寬度。而設計稿往往要求一條完整的分割線。下面提供兩種解法。
這是最常用的做法,也是自訂 cell 時會碰到的方式。
步驟一:關掉系統預設的分割線
// 設置分割線的樣式為None self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
separatorStyle 是個枚舉,按住 command 點進去可以看到全部選項:
typedef NS_ENUM(NSInteger, UITableViewCellSeparatorStyle) {
UITableViewCellSeparatorStyleNone, //不顯示分割線
UITableViewCellSeparatorStyleSingleLine, // 單線
UITableViewCellSeparatorStyleSingleLineEtched // 僅支援分組樣式表視圖
};
步驟二:覆寫 setFrame:
注意這個方法要寫在自訂的 UITableViewCell 子類中。
- (void)setFrame:(CGRect)frame {
frame.origin.y += 1; // 讓cell的y值增加1(根據自己需要分割線的高度來進行調整)
frame.size.height -= 1; // 讓cell的高度減1
[super setFrame:frame]; // 別忘了重寫父類方法
}
透過讓 cell 之間露出一 pixel 的間隙,背景色透出來就形成了自訂的分割線。顏色跟著 tableView 的 backgroundColor 走,想換色只要改這個屬性即可。
這種方式不必自訂 cell,用系統預設的 cell 就行。
iOS 7 中,cell 左側預設有 15pt 的內縮,設定 setSeparatorInset:UIEdgeInsetsZero 就能去掉;但到了 iOS 8,這行設定單獨使用已經失效,還必須一併處理 layoutMargins。
先在 viewDidLoad 中寫:
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
// 如果tableView響應了setSeparatorInset: 這個方法,我們就將tableView分割線的內邊距設為0
[self.tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
// 如果tableView響應了setLayoutMargins: 這個方法,我們就將tableView分割線的間距設為0
[self.tableView setLayoutMargins:UIEdgeInsetsZero];
}
再在 tableView 的代理方法中補上 cell 層級的設定:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
// 這兩句的含義跟上面兩句代碼相同
if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
[cell setSeparatorInset:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
為什麼一定要寫 willDisplayCell?因為 iOS 8 之後,cell 的 layoutMargins 預設沿用 tableView 的設定,而 tableView 的 layoutMargins 又會被系統依 Localized Standard 動態調整。只在 viewDidLoad 設一次,cell 在實際顯示時仍可能被覆蓋回預設值,所以必須在 willDisplayCell 中再設一遍,這也是許多人「明明設了卻沒效果」的原因。
方法二改動最小,適合沿用系統 cell 的場景;方法一可控性最高,能自由決定線的粗細、顏色與縮排,但要搭配自訂 cell。若設計稿要求的是「文字起始處開始的線」而非通到底,那麼方法二的 UIEdgeInsets 寫法反而更直接——把 left 設成與文字左緣相同的值即可。