如何優雅的隱藏UITableView中最后一條分割線?
這個問題是很常見,卻又不太容易解決的。
可能通常的做法都是隱藏UITableView的分割線,自定義一條。
最近在使用彈出菜單的時候,同樣遇到了這個問題。
需求場景,做一個類似微信公眾號,底部菜單彈出的菜單視圖。
而這樣的菜單中的tableView一般contentSize等於其frame.size,並且tableView的scrollEnabled為NO。
我想了一種方法(創建一個高度為1px的UIView,蓋住tableView的底部1px):
UIView *lineView = [self viewWithTag:201]; if (!lineView) { lineView = [[UIView alloc] initWithFrame:CGRectZero]; } lineView.frame = CGRectMake(5, menuRect.size.height-2, menuRect.size.width - 10, 2); lineView.tag = 201; lineView.backgroundColor = [FTPopOverMenuConfiguration defaultConfiguration].tintColor; [self insertSubview:lineView aboveSubview:self.menuTableView];
然而,作者給出了一個很優雅的做法,只需要添加幾行代碼即可,關鍵代碼如下:
if (indexPath.row == _menuStringArray.count-1) { menuCell.separatorInset = UIEdgeInsetsMake(0, self.bounds.size.width, 0, 0); }else{ menuCell.separatorInset = UIEdgeInsetsMake(0, FTDefaultMenuTextMargin, 0, 10+FTDefaultMenuTextMargin); }
我們只需要在CellForRow
方法中判斷是最后一個cell,然后將分割線偏移出屏幕外即可。
注意:
經過測試,上面這種設置cell的separatorInset,來讓最后一條分割線不顯示出來的做法,
對自定義的Cell有效;
對於UITableViewCell,修改了separatorInset,會導致textLabel也隨着偏移。