自定义分割线,当有数据的时候,才出现分割线,比如只有二条数据,那自然就不用出现满屏的分割线
主流做法:
往cell中添加一根分割线,先去掉默认的分割线,然后在每个对应的cell上添加分割线
补充:取消分割线:
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;//没有分割线
做法:自定义UITableViewCell
这里牵连到UITableViewCell中多个方法的生命周期,一个很好的模板:
自定义UITableViewCell声明
//
#import <UIKit/UIKit.h>
@class Contact;
@interface ContactTableViewCell : UITableViewCell
@property(nonatomic, strong) Contact *contact;
+ (instancetype)cellWithTableView:(UITableView *) tableview;
@end
//
自定义UITableViewCell实现
#import "ContactTableViewCell.h"
#import "Contact.h"
@interface ContactTableViewCell()
@property(nonatomic, weak) UIView *dividerView;
@end
@implementation ContactTableViewCell
/**
* 构造方法封装
*/
+ (instancetype)cellWithTableView:(UITableView *) tableview
{
static NSString *ID = @"contact";
return [tableview dequeueReusableCellWithIdentifier:ID];
}
/**
* 如果cell方法是从storyboard或者xib来创建,就会调用这个方法来初始化cell
* 这里负责子控件的添加,而子控件的大小位置在layoutSubviews中更好
*/
- (void)awakeFromNib
{
UIView *divider = [[UIView alloc] init];
divider.backgroundColor = [UIColor blackColor];
divider.alpha = 0.3;
[self.contentView addSubview:divider];
self.dividerView = divider;
}
/**
* 最重要的
* 在这个方法中设置子控件最好
* 原理:当我们cell的frame发生改变就会调用这个方法,而这里拿到cell的frame才是最真实的
*/
- (void)layoutSubviews
{
[super layoutSubviews];
//设置子frame(大小和位置)
CGFloat dividerW = self.frame.size.width;
CGFloat dividerH = 1;
CGFloat dividerX = 0;
CGFloat dividerY = self.frame.size.height - dividerH;
self.dividerView.frame = CGRectMake(dividerX, dividerY, dividerW, dividerH);
}
/**
* 如果cell是通过storyboard或者xib来创建,就不可能调用这个方法来初始化cell
* 如果cell是手写代码方式创建,才会调用这个方法来初始化
*
*/
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
return self;
}
/**
* 封装数据
*/
-(void)setContact:(Contact *)contact
{
_contact = contact;
self.textLabel.text = contact.name;
self.detailTextLabel.text = contact.phone;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
}
@end
//
UITableView自定义每行分割线
最新推荐文章于 2020-12-23 06:28:32 发布