iOS系統(tǒng)中UITableViewCell分割線設置和分割線偏移處理
iOS項目中大量使用到UITableView乘瓤,為了美觀可能需要對UITableViewCell的分割線進行特別的處理臭蚁。如果UITableViewCell簡單的話,為了快速開發(fā)蹭睡,直接使用系統(tǒng)的UITableViewCell,然后直接設置tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine既可以,這在ios7以前是沒有問題的,但是iOS8以后蛔钙,直接設置cell.seperatorInsets 已經(jīng)不生效了储矩。原因是iOS8以后系統(tǒng)給UIView增加了layoutMargins感耙,在UIView 中可以看到如下定義:
@property (nonatomic) UIEdgeInsets layoutMargins NS_AVAILABLE_IOS(8_0);
如果想使用系統(tǒng)的分割線,可以通過下面方法設置:
1.在viewDidLoad方法中添加下面代碼:
/**
* UITableView
*/
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[self.tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
[self.tableView setLayoutMargins:UIEdgeInsetsZero];
}
- 實現(xiàn)UITableView中的tableView:willDisplayCell:forRowAtIndexPath:代理方法持隧,代碼如下:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
// 設置需要的偏移量,這個UIEdgeInsets左右偏移量不要太大即硼,不然會titleLabel也會便宜的。
UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
if ([cell respondsToSelector:@selector(setLayoutMargins:)]) { // iOS8的方法
if (indexPath.row == self.labelArray.count-1) {
[cell setLayoutMargins:UIEdgeInsetsZero];
} else {
// 設置邊界為0屡拨,默認是{8,8,8,8}
[cell setLayoutMargins:inset];
}
}
if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
if (indexPath.row == self.labelArray.count-1) {
[cell setSeparatorInset:UIEdgeInsetsZero];
} else {
[cell setSeparatorInset:inset];
}
}
}
效果如下:
demo.png
如果你不想使用系統(tǒng)的效果只酥,你可以在UITableCell中自己繪制分割線,但是處理合理的話呀狼,利用系統(tǒng)的效果也不錯裂允,至少相對簡單些。