iOS学习之UI自定义cell(等高,不等高,自适应)

一、自定义Cell

  • 为什么需要自定义cell:系统提供的cell满足不了复杂的样式,因此:自定义Cell和自定义视图一样,自己创建一种符合我们需求的Cell并使用这个Cell。如下图所示的这些Cell都是通过自定义Cell样式实现的:
  • 自定义Cell的步骤:

    1.首先创建一个继承于UITableViewCell的类:(这是一个简易的通讯录的自定义cell)

复制代码
@interface RootTableViewCell : UITableViewCell
// 联系人头像
@property (nonatomic, strong) UIImageView *headerImageView;
// 联系人姓名label
@property (nonatomic, strong) UILabel *nameLabel;
// 电话号码的label
@property (nonatomic, strong) UILabel *phoneLabel;
@end
复制代码

    2.实现UITableViewCell的初始化方法:

复制代码
@implementation RootTableViewCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // 初始化子视图
        [self initLayout];
    }
    return self;
}

- (void)initLayout
{
    // 1.头像
    self.headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(16, 10, 100, 100)];
//    self.headerImageView.backgroundColor = [UIColor orangeColor];
    self.headerImageView.layer.masksToBounds = YES;
    self.headerImageView.layer.cornerRadius = 50;
    // cell提供了一个contentView的属性,专门用来自定义cell,防止在cell布局的时候发生布局混乱,如果是自定义cell,记得将子控件添加到ContentView上
    [self.contentView addSubview:self.headerImageView];
    
    // 2.姓名
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.headerImageView.frame) + 10, CGRectGetMinY(self.headerImageView.frame), 100, 40)];
//    self.nameLabel.backgroundColor = [UIColor redColor];
    [self.contentView addSubview:self.nameLabel];
    
    // 3.电话号码
    self.phoneLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.nameLabel.frame), CGRectGetMaxY(self.nameLabel.frame) + 20, 200, 40)];
//    self.phoneLabel.backgroundColor = [UIColor greenColor];
    [self.contentView addSubview:self.phoneLabel];
    
}
复制代码
  • 注意:
  • 确保所有的你想添加的子视图都在自定义Cell的初始化方法中创建,由于UITableView的重用机制,一个Cell在第一次创建成功并用于下一次显示的时候,不会再走初始化方法,这样可以避免子视图的重复创建。
  • 在Cell的子视图创建成功后,将子视图设置为属性,类似于UITableViewCell所自带的textLabel和detailTextLabel属性。便于在UITableView的协议中给自定义视图赋值。

二、Model类型对象的使用

  • Model类概述:
  • Model类主要是为了给我们提供数据,简单的说即自定义类且继承于NSObject的称之为Model。(前面OC学到的KVC就是帮助我们将字典转换为Model类。)
  • 在自定义Cell中使用Model类存放数据:
  • 首先创建Model类并继承于NSObject
  • 然后添加和字典中对应的属性
  • 在视图控制器中将字典通过KVC为Model赋值
  • 将Model对象添加到数组中并刷新TableView
复制代码
// 建立model存放数据
@interface Contact : NSObject
// 姓名
@property (nonatomic, copy) NSString *name;
// 手机号码
@property (nonatomic, copy) NSString *phoneNumber;
// 图片名
@property (nonatomic, copy) NSString *imageName;
@end
复制代码
复制代码
#import "RootTableViewController.h"
#import "Contact.h"
#import "RootTableViewCell.h"
@interface RootTableViewController ()
// 声明一个大数组存放所有联系人
@property (nonatomic, strong) NSMutableArray *allContactsArray;

@end

@implementation RootTableViewController
// 懒加载 (重写getter方法)
- (NSMutableArray *)allContactsArray
{
    if (_allContactsArray == nil) {
        _allContactsArray = [NSMutableArray array];
    }
    return _allContactsArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"通讯录";
    self.navigationController.navigationBar.barTintColor = [UIColor lightGrayColor];
    [self handleData];

}

- (void)handleData
{
    // 读取plist文件
    NSMutableArray *array =[NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Contacts" ofType:@"plist"]];
    // 将要显示的数据转为model对象
    for (NSDictionary *contactDict in array) {
        Contact *contact = [[Contact alloc] init];
        // 使用KVC赋值
        [contact setValuesForKeysWithDictionary:contactDict];
        // 将联系人model存放在大数组中
        [self.allContactsArray addObject:contact];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return self.allContactsArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 创建常量标识符
    static NSString *identifier = @"cell";
    // 从重用队列里查找可重用的cell
    RootTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    // 判断如果没有可以重用的cell,创建
    if (!cell) {
        cell = [[RootTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    // 设置数据
    // 取出model对象
    Contact *contact = self.allContactsArray[indexPath.section];
    cell.headerImageView.image = [UIImage imageNamed:contact.imageName];
    cell.nameLabel.text = contact.name;
    cell.phoneLabel.text = contact.phoneNumber;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

@end
复制代码

  3.运行效果如下图:

三、多种Cell混合使用

  • 一个重用标识符只能针对于一种Cell样式,不同的Cell需要基于不同的重用标识符来进行区分,而重用标识符的区分需要根据不同的情况来划分,比如:
  • model属性划分(不同的数据内容,比如一个数据中有type字段,为1代表图片类型,为0代表文字类型等)
  • 固定的行显示的Cell类型不一样
复制代码
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier1 = @"labelCell";
    static NSString *identifier2 = @"imageCell";
    Person *person = self.allPersonsArray[indexPath.row];
    if ([person.type isEqualToString:@"1"]) {
        LableCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier1 forIndexPath:indexPath];
        cell.nameLabel.text = person.name;
        cell.statusLabel.text = person.status;
        return cell;
        
    }else {
        ImageViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier2 forIndexPath:indexPath];
        cell.nameLabel.text = person.name;
        cell.statusLabel.text = person.status;
        cell.myImageView.image = [UIImage imageNamed:person.imageName];
        return cell;
    }
    
}
复制代码

四、Cell自适应高度

  • 当每个Cell都有不同的高度时,就需要Cell去自适应高度
  • 方式为两种:
  • 文本自适应高度:根据文本内容设定Label高度
  • 图片自适应高度:根据图片宽度进行等比例缩放
  • 这里需要创建一个新的类去封装这两个方法用以获得文本的高度和图片的高度:
复制代码
@interface CalculateTextHeight : NSObject

// 声明类方法用来计算文本高度
+ (CGFloat)calculateTextHeightWithText:(NSString *)text
                                  font:(UIFont *)font;

+ (CGFloat)imageHeightWithImage:(UIImage *)image;

@end
复制代码
  • 具体的实现
复制代码
@implementation CalculateTextHeight
+ (CGFloat)calculateTextHeightWithText:(NSString *)text font:(UIFont *)font
{
    // iOS7.0中求文本高度的方法,返回一个CGRect的高度
    
    // 第一个参数,一个屏幕宽,10000高的文本
    CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width, 10000);
    // 第二个参数,设置以行高为单
    // 第三个参数,根据字体判断高度
    CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : font} context:nil];
    
    return rect.size.height;
    
}


+ (CGFloat)imageHeightWithImage:(UIImage *)image
{
    // 得到图片的宽和高
    CGFloat width = image.size.width;
    CGFloat height = image.size.height;
    // 得到宽高比例和屏幕宽度
    float i = height / width;
    float j = [UIScreen mainScreen].bounds.size.width;
    CGFloat x = i * j;
    return x;
}

@end

猜你喜欢

转载自blog.csdn.net/Mr_tangIT/article/details/80620115