iOS9 UITableViewCell 分割线左顶头

UITableViewCell在IOS6下分割线是默认顶头的,在IOS7以后左边会有一定的间距(15)。

网上有一些解决办法,分享我找到的最简单的一种:在数据源方法tableView:cellForRowAtIndexPath:中加入如下三行

        cell.preservesSuperviewLayoutMargins = NO;
        cell.separatorInset = UIEdgeInsetsZero;
        cell.layoutMargins = UIEdgeInsetsZero;

需要注意的是preservesSuperviewLayoutMarginslayoutMargins是iOS8以后才有的,separatorInset是iOS7以后才有的,如果要兼容以前的版本记得先判断selector是否存在。

至于原因如下:

Setting the separatorInset of tableView to UIEdgeInsetsZero is not going to work. It will only effect the extra separators, not the cells that you created.
iOS8 introduces layoutMargins property on UIView, along with another property called preservesSuperviewLayoutMargins indicating whether superview’s layoutMargins is preserved (Think of it as an override) which is YES by default. layoutMargins property is a set of insets from the edge of the view’s bounds that denote a default spacing for laying out content.
The default separatorInset of tableView and tableViewCell is (top = 0, left = 15, bottom = 0, right = 0)
The default layoutMargins of tableView and tableViewCell is (top = 8, left = 8, bottom = 8, right = 8)
These 3 properties are defining the behaviour of separator indentation.
However, setting tableView’s layoutMargins is not going to effect tableViewCell. Because tableViewCell’s superview is not tableView. It’s tableView’s subView, an instance of UITableViewWrapperView whose superClass is UIScrollView and whose layoutMargins is (top = 8, left = 15, bottom = 8, right = 15) and preservesSuperviewLayoutMargins is YES.
You have to set separatorInset and layoutMargins of tableViewCell directly:
tableViewCell.preservesSuperviewLayoutMargins = NO;
tableViewCell.separatorInset = UIEdgeInsetsZero;
tableViewCell.layoutMargins = UIEdgeInsetsZero;
You can put those code in cell’s init method or awakeFromNib or tableView’s delegate tableView:willDisplayCell:fromRowAtIndexPath, etc.

大致的意思是说iOS7只有separatorInset的概念,在IOS7下tableView的分割线左边有15像素的间距。

iOS8中还有layoutMargins,用来表示子view和父view的间距,有8像素的间距。preservesSuperviewLayoutMargins默认为true表示开启子view与父view的间距。


References:
《iOS8 UITableView 分割线顶头》
《iOS7 tableview separatorInset cell分割线左对齐》

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值