AZZ的博客

简单的,才是最好的。

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分割线左对齐》

阅读更多
版权声明:本文为博主原创文章,转载请标明原文地址以及作者(阿曌)。 https://blog.csdn.net/XieYupeng520/article/details/51539601
个人分类: * iOS基础
上一篇iOS 如何更改Cell中默认accessoryView的位置
下一篇小坑:UITableView分组后最后一根分割线不显示
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭