您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 8 中 UITableView 分割線無法去除 15px 空白間距的解法

編輯:iOS 開發綜合

在 iOS 8 中,許多開發者發現原本用來消除 UITableView 分割線左右空白間距的 setSeparatorInset:UIEdgeInsetsZero 突然失效了——分割線兩側依然保留著約 15px 的縮排。本文將提供一套可靠的解決辦法。

問題背景

在早期 iOS 版本中,只要將 separatorInset 設為 UIEdgeInsetsZero,分割線就能貼齊邊緣。但到了 iOS 8,這招卻不再管用。原因是蘋果在 iOS 8 引入了 layoutMargins 屬性,分割線的實際位置會同時受到 cell 與 tableView 兩者的 layoutMargins 影響。

解決步驟一:設定 tableView 的屬性

首先在 viewDidLoad 方法中,同時將 tableView 的 layoutMargins 與 separatorInset 都設為零:

if (leftTable!.respondsToSelector("setLayoutMargins:")) {
    leftTable?.layoutMargins = UIEdgeInsetsZero
}
if (leftTable!.respondsToSelector("setSeparatorInset:")) {
    leftTable!.separatorInset = UIEdgeInsetsZero;
}

解決步驟二:設定每個 cell 的屬性

僅設定 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 的分割線就能緊貼邊緣、不再有任何空白間距了。希望這個解法能幫你解決困擾已久的分割線問題!

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved