58.iOS6 7 cell适配 tableView背景

1.设置tableView的背景
// 设置tableview的背景颜色
self.tableView.backgroundColor =  [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg"]];
// 清空系统的backgroundView
self.tableView.backgroundView = nil;
//backgroundView的优先级高于backgroundColor
2.iOS6.7的cell适配
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
     // 初始化操作
     // 1.设置背景颜色
     [self setupBackground];
     // 2. 清空子控件
     [self clearSubView];
     // 设置cell的宽度和屏幕一样宽
     // 3.添加分割线
     [self addDivider];
    }
    return self;
}

- (void)addDivider
{
    //由于清空了cell自带的背景,这个时候cell的分割线也没有了,需要自定义
    if (!iOS7) {
        UIView *divider = [[UIView alloc] init];
        divider.backgroundColor = [UIColor blackColor];
        [self.contentView addSubview:divider];
        divider.alpha = 0.4;
        self.divider = divider;
    }
}

- (void)clearSubView
{
    // 3.清空子视图的背景颜色(子控件也是有背景颜色的,所以要清空子控件的颜色)
    self.textLabel.backgroundColor = [UIColor clearColor];
    self.detailTextLabel.backgroundColor = [UIColor clearColor];
}

- (void)setupBackground
{
    // 1.设置cell选中状态的背景颜色(在iOS6中cell不是方形,是由于背景造成的)
    UIView *selView = [[UIView alloc] init];
    selView.backgroundColor = NJColor(232, 228, 209);
    self.selectedBackgroundView = selView;

    // 2.设置cell默认状态的背景颜色
    UIView *norView = [[UIView alloc] init];
    norView.backgroundColor = [UIColor whiteColor];
    self.backgroundView = norView;
}

// cell的frame是系统管理的, 系统会自动给cell设置frame
// 重写该方法拦截系统设置的cell,自定义cellframe
- (void)setFrame:(CGRect)frame
{
    //cell的宽度是屏幕的宽度,显示的是contentView,contentView在cell的左右两边都有10的间距,这个时候将cell的宽度加20,并且将x左移10,这个时候contentView就会是整个屏幕的宽度
    if (!iOS7) {
        // 修改cell的宽度
        frame.size.width += 20;
        frame.origin.x -= 10;
    }
    [super setFrame:frame];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    CGFloat dividerX = 0;
    //因为cell可能有辅助视图,这个时候contentView的宽度就会减去辅助视图的宽度,这个时候分割线就不会全屏,所以用的是整个屏幕的宽度
//    CGFloat dividerW = self.contentView.frame.size.width;
    CGFloat dividerW = [UIScreen mainScreen].bounds.size.width;
    CGFloat dividerH = 1;
    CGFloat dividerY = self.contentView.frame.size.height - dividerH;

    self.divider.frame = CGRectMake(dividerX, dividerY, dividerW, dividerH);

//  NSLog(@"setFrame = %@", NSStringFromCGRect(self.contentView.frame));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值