iOS中让cell分割线顶头的四种终极方法实现:从小白到装x

iOS中让cell分割线顶头在可认知的范围内,一共有四种办法。但是度娘一抄一大把,往往给出的方法都是舍近求远。很多小白也是两眼一闭,拿来就复制粘贴。

以后不要再求人了,也不用在度娘了。记住下面的方法,足够应对各种场景了。

1 iOS8以前

iOS8以前需要在controller中以下两个方法中进行约束。

- (void)viewDidLoad { [super viewDidLoad]; self.tableView.separatorInset = UIEdgeInsetsZero; self.tableView.layoutMargins = UIEdgeInsetsZero;}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { cell.layoutMargins = UIEdgeInsetsZero; cell.separatorInset = UIEdgeInsetsZero;}

2 iOS8以后三种方法

2.1 在数据源方法中

在数据源方法tableView:cellForRowAtIndexPath:中,加入以下代码。


cell.preservesSuperviewLayoutMargins = NO; cell.separatorInset = UIEdgeInsetsZero; cell.layoutMargins = UIEdgeInsetsZero;
  • 需要注意的是preservesSuperviewLayoutMargins和layoutMargins是iOS8以后才有的,separatorInset是iOS7以后才有的。

  • iOS7只有separatorInset的概念,在IOS7下tableView的分割线左边有15像素的间距。

  • iOS8中layoutMargins,用来表示子view和父view的间距,有8像素的间距。

  • preservesSuperviewLayoutMargins默认为true表示开启子view与父view的间距。

2.2 在controller中

还有一种最简单的方法,只需要在controller的didviewloaded中加入一句话就可以了。


self.tableView.separatorInset = UIEdgeInsetsZero;

  • 需要注意的是,tablveView的separatorInset这个属性是在iOS7之后才出现的。官方是这么描述的:
//NS_AVAILABLE_IOS(7_0) UI_APPEARANCE_SELECTOR; 
// allows customization of the frame of cell separators
@property (nonatomic) UIEdgeInsets separatorInset

2.3 最装x的办法:自己重绘分割线

这种办法不太好讲。为了效率,当然是越简单越好,肯定不会挑这种办法。当然如果为了装x,就另当别论。但是很多时候装x没有装好,就变装13了。小心!


// 画分割线 
UIView *lineView = [[UIView alloc] init]; lineView.backgroundColor = [UIColor lightGrayColor]; 
[self.contentView addSubview:lineView];

 // 获取屏幕压缩比例"缩放比例" 如果是1x屏幕比率就是1 如果是2x 比率就是2 如果是3x 比率就是3 
CGFloat scale = [UIScreen mainScreen].scale; 
[lineView mas_makeConstraints:^(MASConstraintMaker *make) { 
    make.left.right.offset(0); 
    make.top.equalTo(deleteBtn.mas_bottom).offset(margin);
// 让分割线的高为永远都是1个像素 
make.height.offset(1 / scale); }];
  • 因为苹果的屏幕有1x,2x,3x。所以平时在计算位置的时候都是按照像素点来计算的,如果真的是要按照像素计算,必须要把屏幕的缩放比例考虑进去。

  • 用来表示1像素 :1 / [UIScreen mainScreen].scale

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容