Implement a public custom UITableviewCell

1. Function introduction
: First, the renderings:
A custom cell implements different layouts

Implementation styles are:

  1. Title+Arrow;
  2. Title+Subtitle+Arrow
  3. title + subtitle
  4. title
  5. Image+Title+Arrow
  6. Picture + title

Next, let’s explain how to implement such a multifunctional, reusable, and more flexible custom UITableViewCell through Masonry automatic adaptation: 1.
First, look at the project structure:
Project structure

Use CocoaPods for third-party library management (I will write a separate blog later on how to install CocoaPods and the problems that arise during the installation, so stay tuned!). In this project, I only imported the Masonry third-party library. Other libraries are needed if needed. You can import it yourself.

2. Look at these macros defined in the pch file

#ifndef PrefixHeader_pch
#define PrefixHeader_pch
//以下是自动适配相关宏定义 不用自动适配可以无视
#define WS(weakSelf)  __weak __typeof(&*self)weakSelf = self;
//define this constant if you want to use Masonry without the 'mas_' prefix
#define MAS_SHORTHAND
//define this constant if you want to enable auto-boxing for default syntax
#define MAS_SHORTHAND_GLOBALS
/**
 *  RGB值方式
 */
#define RGBA(r,g,b,a)     [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:a]
#define RGB(r,g,b)          RGBA(r,g,b,1)
#define COLOR_DETAIL        RGB(109, 116, 121)  //CELL 描述颜色
/**
 *  字号设置
 */
#define FONT(RatioFont)     [UIFont systemFontOfSize:RatioFont]
#define COLOR_TITLE         RGB(41, 46, 49)  //CELL title颜色
// Include any system framework and library headers here that should be included in all compilation units.
// You will also need to set the Prefix Header build setting of one or more of your targets to reference this file.
#ifdef __OBJC__
#import "Masonry.h"

#endif
#endif /* PrefixHeader_pch */
  • The Masonry adaptation method has been standardized to make it easier to adapt. Of course, this is just a personal preference. If you are not used to it, you can also use your own method for adaptation;
  • Define RGB colors and enter the corresponding RGB parameters to customize various colors. Compared with [UIColor redColor], it is more flexible and more arbitrary;
  • Font is a macro for setting the font size. To set the font size, just pass in the font size directly;

3. Cell implementation part
<1>. Expose a method to set the cell in our CommonTableViewCell.h file, so that different parameters can be passed in when calling. The code is as follows (the comments are already very clear, so I won’t explain them one by one) O(∩_∩)O):

/**
 对外暴露设置cell方法
 @param imageName 传入图片名字
 @param title 标题
 @param subTitle 副标题
 @param isHas 是否有arrow
 */
-(void)setCellInfoWithHeaderImage:(NSString *)imageName withTitle:(NSString *)title withSubTitle:(NSString *)subTitle withArrow:(BOOL )isHas;

<2>. Carry out UI interface layout and implement setting methods in our CommonTableViewCell.m file:

  • Add required controls
@property (nonatomic, strong)UIImageView *headerImageView;  //  标题图片
@property (nonatomic, strong)UILabel *titleLabel;  //  标题
@property (nonatomic, strong)UILabel *subTitleLabel; //  副标题
@property (nonatomic, strong)UIImageView *arrowImageView; // arrow图片
  • Initialize our custom cell:
//  这里我们把搭建UI和适配的方法抽离出来,使得代码可读性更高,不至于太多冗杂
 - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]){
        [self bulidUI]; //  搭建UI
        [self autoLayout]; //  UI界面控件自适应
    }
    return self;
}
  • bulidUI (you can also choose lazy loading here)
-(void)bulidUI{
    //  添加图片 headerImage
    self.headerImageView = [[UIImageView alloc] init];
    [self.contentView addSubview:self.headerImageView]; 
    //  添加标题 titleLabel
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.font = [UIFont systemFontOfSize:14];
    self.titleLabel.textColor = [UIColor blackColor];
    [self.contentView addSubview:self.titleLabel];
    //  添加副标题 subTitleLabel
    self.subTitleLabel = [[UILabel alloc] init];
    self.subTitleLabel.textColor = [UIColor lightGrayColor];
    self.subTitleLabel.textAlignment = NSTextAlignmentRight;
    self.subTitleLabel.font = [UIFont systemFontOfSize:12];
    [self.contentView addSubview:self.subTitleLabel];
    //  添加arrow
    self.arrowImageView = [[UIImageView alloc] init];
    [self.contentView addSubview:self.arrowImageView];
}
  • autoLayout automatic adaptation
-(void)autoLayout{
        //  对头部图片进行约束
    [self.headerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.offset(10);
        make.centerY.equalTo(self.contentView.mas_centerY);
        make.height.equalTo(21);
        make.width.equalTo(21);
    }];
    //  对标题进行约束
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.headerImageView.mas_trailing).offset(10);
        make.height.equalTo(21);
        make.centerY.equalTo(self.contentView.mas_centerY);
        make.trailing.equalTo(self.subTitleLabel.mas_leading).offset(-10);
    }];
    //  对副标题进行约束
    [self.subTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.titleLabel.mas_trailing).offset(10);
        make.height.equalTo(21);
        make.centerY.equalTo(self.contentView.mas_centerY);
        make.trailing.equalTo(self.arrowImageView.mas_leading).offset(-10);
    }];
    //  对arrow进行约束
    [self.arrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.contentView.mas_trailing).offset(-10);
        make.width.equalTo(8);
        make.height.equalTo(13);
        make.centerY.equalTo(self.contentView.mas_centerY);
    }];
}
  • Implement methods to set cell display
- (void)setCellInfoWithHeaderImage:(NSString *)imageName withTitle:(NSString *)title withSubTitle:(NSString *)subTitle withArrow:(BOOL)isHas {
    if (imageName.length<=0){ //  判断头部照片是否存在
        [self.titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
           make.leading.offset(10); //  没有头部照片,更新约束,此时标题靠左边
        }];
    }
    if (subTitle.length>0) { //  判断副标题是否有,有则更新约束
        [self.titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_greaterThanOrEqualTo(80);  //  设置标题宽度
        }];
        [self.subTitleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_greaterThanOrEqualTo(80); //  设置副标题宽度
        }];
    }
    if (!isHas){  //  判断如果是否有arrow
        [self.subTitleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
           make.trailing.equalTo(self.contentView.mas_trailing).offset(-10);
        }];
    }
    self.headerImageView.image = [UIImage imageNamed:imageName];
    self.titleLabel.text = title;
    self.subTitleLabel.text = subTitle;
    //  这里我们arrow的图片可以放在本地,直接读取就好,当然也可以在外面传入进来,只需要对暴露方法添加参数即可,可以参照头部图片一样的判断
    self.arrowImageView.image = [UIImage imageNamed:@"ic_arrow right"]; 
}

4. Implementation method:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 创建对象 
    CommonTableViewCell *commonTableViewCell = [tableView dequeueReusableCellWithIdentifier:@"commonTableViewCellIdentifier"];
    if (!commonTableViewCell){
        commonTableViewCell = [[CommonTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"commonTableViewCellIdentifier"];
    }
    switch (indexPath.row) {
            case 0:{
               [commonTableViewCell setCellInfoWithHeaderImage:@"" withTitle:@"标题xxxxxxxx34r34253452345235324" withSubTitle:@"" withArrow:YES];
            }
            break;
        case 1:{
            [commonTableViewCell setCellInfoWithHeaderImage:@"" withTitle:@"标题4523534523453453245" withSubTitle:@"副标题3453453453453452fgfghffjjjfghjfghjfgjfghjfghj3452345234523" withArrow:YES];
        }
            break;
        case 2:{
            [commonTableViewCell setCellInfoWithHeaderImage:@"" withTitle:@"标题" withSubTitle:@"副标题" withArrow:NO];
        }
            break;
        case 3:{
            [commonTableViewCell setCellInfoWithHeaderImage:@"" withTitle:@"标题" withSubTitle:@"" withArrow:NO];
        }
            break;
        case 4:{
            [commonTableViewCell setCellInfoWithHeaderImage:@"per_printer" withTitle:@"标题" withSubTitle:@"副标题" withArrow:YES];
        }
            break;
        case 5:{
            [commonTableViewCell setCellInfoWithHeaderImage:@"per_printer" withTitle:@"标题" withSubTitle:@"" withArrow:YES];
        }
            break;
        default:
            break;
    }
    return commonTableViewCell;

}

So far we have finished talking about the layout and implementation of this public cell. Next, there are several other types of custom cells in our project. If you are interested, you can take a look for yourself. Novices will not go into details here.

The above project code has been uploaded to GitHub. Your criticisms and corrections are welcome. Stars are also welcome!

Guess you like

Origin blog.csdn.net/chuzhaohzi/article/details/57074992