UITableView自定义每行分割线

自定义分割线,当有数据的时候,才出现分割线,比如只有二条数据,那自然就不用出现满屏的分割线
主流做法:
往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
//

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值