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

iOS 8 UITableView 分割線設定 separatorInset = 0 失效

編輯:iOS 開發綜合

iOS 7 的時候在 storyboard 把 TableView 的 separator inset 設為 0,可以讓分割線頂到頭。但升級到 iOS 8 之後,發現這招不管用了。

經過搜尋,在 Stack Overflow 找到了答案,翻譯紀錄如下。

iOS 8 在 cell 與 tableview 中都引入了 layoutMargins 屬性,而這個屬性在 iOS 7 中並沒有,所以需要區別對待這兩個版本。

在 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];
    }
    // 按照作者最後的意思還要加上下面這一段
    if([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]){
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
}

在 tableview 中設定

你還需要在 tableview 上設定同樣的屬性。經過多次試驗,發現可以在 viewDidLayoutSubviews 中設定這個屬性。把下面程式碼複製到你的 view 實作中:

-(void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

這樣在 iOS 7 與 iOS 8 中都能實現分割線頂頭的需求(iOS 6 預設就是頂頭的,因此這個方案可適用於 iOS 6 至 8)。

補充:依原作者後續在 Twitter 上的說法,你可能還需要在 cell 中設定 preservesSuperviewLayoutMargins = NO。再次說明,每個人的情況因人而異。

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