iOS 重构之路 - UITableViewCell

2018-08-31  本文已影响15人  SoaringHeart
思想:通过分类抽出一切通用的方法及参数
OC\:
1.使用:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    WHKTableViewOneCell * cell = [WHKTableViewOneCell cellWithTableView:tableView];
    
    cell.labelLeft.text = @"title";
    cell.imgViewRight.hidden = YES;//箭头
    
//    [cell  getViewLayer];
    return cell;
    
}

2. WHKTableViewOneCell 内部实现
导入类别:
#import "UITableViewCell+AddView.h"//核心

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
     if (self) {
        [self createControls];
        
    }
    return self;
}

- (void)createControls{
    //图片+文字+文字+图片
    [self.contentView addSubview:self.imgViewLeft];
    [self.contentView addSubview:self.imgViewRight];
    
    [self.contentView addSubview:self.labelLeft];
    [self.contentView addSubview:self.labelRight];
    }

-(void)layoutSubviews{
    [super layoutSubviews];
    // 布局自定义
    //图片+文字+文字+图片

}

-----------------------------------------------------------------

Swift:
1.使用:
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: UITableViewCellOne = UITableViewCellOne.cellWithTableView(tableView) as! UITableViewCellOne;
        cell.labelLeft.text = String.init(format: "section_%d,row_%d", indexPath.section,indexPath.row);
        cell.labelRight.text = "990" + "\(indexPath.row)";
        cell.imgViewLeft.image = UIImage(named: "dragon.png");
        cell.imgViewRight.isHidden = false;
        
//        cell.getViewLayer();
        return cell;
    }

2. UITableViewCellOne 内部实现

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier);
       
        //图片+文字+文字+图片
        contentView.addSubview(imgViewLeft);
        contentView.addSubview(imgViewRight);
        
        contentView.addSubview(labelLeft);
        contentView.addSubview(labelRight);
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder);
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews();

        //布局自定义
}

UITableViewCell+AddView.h
UITableViewCellOne.swift

上一篇 下一篇

猜你喜欢

热点阅读