在 iOS 8 中,許多開發者發現原本用來消除 UITableView 分割線左右空白間距的 setSeparatorInset:UIEdgeInsetsZero 突然失效了——分割線兩側依然保留著約 15px 的縮排。本文將提供一套可靠的解決辦法。
在早期 iOS 版本中,只要將 separatorInset 設為 UIEdgeInsetsZero,分割線就能貼齊邊緣。但到了 iOS 8,這招卻不再管用。原因是蘋果在 iOS 8 引入了 layoutMargins 屬性,分割線的實際位置會同時受到 cell 與 tableView 兩者的 layoutMargins 影響。
首先在 viewDidLoad 方法中,同時將 tableView 的 layoutMargins 與 separatorInset 都設為零:
if (leftTable!.respondsToSelector("setLayoutMargins:")) {
leftTable?.layoutMargins = UIEdgeInsetsZero
}
if (leftTable!.respondsToSelector("setSeparatorInset:")) {
leftTable!.separatorInset = UIEdgeInsetsZero;
}
僅設定 tableView 還不夠,還必須在 tableView:cellForRowAtIndexPath: 代理方法中,對每個 cell 做同樣的處理:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (cell!.respondsToSelector("setLayoutMargins:")) {
cell!.layoutMargins = UIEdgeInsetsZero
}
if (cell!.respondsToSelector("setSeparatorInset:")) {
cell!.separatorInset = UIEdgeInsetsZero;
}
// 後續設定 cell 內容...
}
關鍵在於:iOS 8 中 cell 的分割線位置由「cell 自身的 layoutMargins」與「tableView 的 separatorInset」共同決定。只有把兩邊都歸零,分割線才會真正貼齊螢幕邊緣,徹底消除那惱人的 15px 空白。這裡使用 respondsToSelector: 做判斷,是為了兼顧 iOS 8 以下的舊版本,確保程式碼的向下相容性。
按照上述兩個步驟設定後,不出意外的話,Table 的分割線就能緊貼邊緣、不再有任何空白間距了。希望這個解法能幫你解決困擾已久的分割線問題!