2016年8月7日
UITabViewCell自定義分割線
在UITableView的使用中,通常需要設(shè)置分割線暮芭。但是分割線會(huì)經(jīng)常短一截的情況想鹰,針對(duì)這個(gè)情況,有三種方式可以解決。
1 自定義UIView充當(dāng)分割線
實(shí)現(xiàn)原理德召,自定義CMTableViewCell繼承自UITableViewCell白魂,使用懶加載創(chuàng)建高度為1的UIView,重寫(xiě)layoutSubViews布局UIView的位置。
自定義cell的.m文件
@interface CMTableViewCell ()
@property(nonatomic,weak) UIView *separatorView;
@end
@implementation CMTableViewCell
//使用懶加載創(chuàng)建分割線view,保證一個(gè)cell只有一條
-(UIView *)separatorView
{
if (_separatorView == nil) {
UIView *separatorView = [[UIView alloc]init];
self.separatorView = separatorView;
separatorView.backgroundColor = [UIColor redColor];
[self addSubview:separatorView];
}
return _separatorView;
}
//重寫(xiě)layoutSubViews方法上岗,設(shè)置位置及尺寸
-(void)layoutSubviews
{
[super layoutSubviews];
self.separatorView.frame = CGRectMake(0, self.bounds.size.height-1, self.bounds.size.width, 1);
}
2 修改系統(tǒng)屬性--主要是系統(tǒng)適配
iOS6的時(shí)候cell的分割線是屏幕寬的福荸,但是現(xiàn)在不是了,向右縮進(jìn)了一些距離
iOS7的時(shí)候肴掷,蘋(píng)果對(duì)tableView增加了一個(gè)叫separatorInset的東西敬锐,會(huì)改變分割線的邊距
iOS8,內(nèi)部增加一些自動(dòng)布局的東西呆瞻,我們可以在storyboard添加約束的時(shí)候可以感受到台夺,每次添加約束的時(shí)候,都會(huì)勾掉一個(gè)叫constraint to margins的選項(xiàng)痴脾。--所以這個(gè)我們需要注意
所以颤介,我們可以通過(guò)修改這些屬性得到答案
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//都是針對(duì)tableView來(lái)看
//1 去除掉自動(dòng)布局添加的邊距
self.tableView.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0);
//2 去掉iOS7的separatorInset邊距
self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 20;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
}
cell.textLabel.text = @"haha";
//去掉cell的自動(dòng)布局添加的邊距
cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0);
return cell;
}
3 巧妙利用TableView的背景作為分割線---萬(wàn)能方式
這個(gè)方式的巧妙之處在于,保持每個(gè)cell的位置不變赞赖,也就是坐標(biāo)仍然位置系統(tǒng)自動(dòng)計(jì)算好的滚朵,調(diào)整cell的高度,讓后邊的tableView露出來(lái)前域,利用tableView的背景色作為分割線辕近。
關(guān)鍵點(diǎn):tableView的cell,在初始化的時(shí)候frame就已經(jīng)全部計(jì)算好了匿垄,當(dāng)cell即將顯示的時(shí)候會(huì)調(diào)用setFrame方法來(lái)給cell賦值亏推,所以,我們就可以重寫(xiě)setFrame方法攔截年堆,修改frame里面的height吞杭,達(dá)到目的。
CMTableViewCell.m文件
- (void)viewDidLoad {
[super viewDidLoad];
//1 禁用系統(tǒng)自帶的分割線
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//2 設(shè)置tableView的背景色跟系統(tǒng)自帶的背景色一致 198 198 203
self.tableView.backgroundColor = [UIColor colorWithRed:198/255.0 green:198/255.0 blue:203/255.0 alpha:1];
//3 重寫(xiě)cell的setFrame的方法-在自定義cell中設(shè)置
}
CMTableCell.m文件
//3 重寫(xiě)setFrame方法
-(void)setFrame:(CGRect)frame
{
//只修改高度
frame.size.height-=1;
//調(diào)用系統(tǒng)方法設(shè)置
[super setFrame:frame];
}