iOS代码自定义UITableView Cell(每个Cell的高度不一样)

1.新建一个继承自UITableViewCell的类 @interface ViewController : UITableViewController


2.重写initWithStyle:reuseIdentifier:方法

添加所有需要显示的子控件(不需要设置子控件的数据和frame,  子控件要添加到contentView中)

进行子控件一次性的属性设置(有些属性只需要设置一次, 比如字体\固定的图片)


@interface StatusCell()

/**

 *  头像

 */

@property (nonatomic, weak) UIImageView *iconView;

/**

 *  昵称

 */

@property (nonatomic, weak) UILabel *nameView;


@end


@implementation StatusCell

/**

 *  构造方法(在初始化对象的时候会调用)

 *  一般在这个方法中添加需要显示的子控件

 */

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

{

    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    if (self) {

        // 1.头像

        UIImageView *iconView = [[UIImageView alloc] init];

        [self.contentView addSubview:iconView];

        self.iconView = iconView;

        

        // 2.昵称

        UILabel *nameView = [[UILabel alloc] init];

        nameView.font = NameFont;

        [self.contentView addSubview:nameView];

        self.nameView = nameView;

     

    }

    return self;

}



3.提供2个模型

data 数据模型: 存放文字数据\图片数据


@interface Status : NSObject

@property (nonatomic, copy) NSString *name; // 内容

@property (nonatomic, copy) NSString *icon; // 头像

@end


frame模型: 存放数据模型\所有子控件的frame\cell的高度,最好设置readonly属性,防止被意外修改


/**

 *  昵称的frame

 */

@property (nonatomic, assign, readonly) CGRect nameF;


4.Cell设置加载中拥有一个frame模型(不要直接拥有数据模型)


5.重写frame模型属性的setter方法: 在这个方法中设置子控件的显示数据和frame

/**

 *  在这个方法中设置子控件的frame和显示数据

 */

- (void)setStatusFrame:(StatusFrame *)statusFrame

{

    _statusFrame = statusFrame;

    

    // 1.设置数据

    [self settingData];

    

    // 2.设置frame

    [self settingFrame];

}

/**

 *  设置数据

 */

- (void)settingData

{

    // 微博数据

    Status *status = self.statusFrame.status;

    

    // 1.头像

    self.iconView.image = [UIImage imageNamed:status.icon];

    

    // 2.昵称

    self.nameView.text = status.name;

 

}

/**

 *  计算文字尺寸

 *

 *  @param text    需要计算尺寸的文字

 *  @param font    文字的字体

 *  @param maxSize 文字的最大尺寸

 */

- (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize

{

    NSDictionary *attrs = @{NSFontAttributeName : font};

    return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;

}



6.frame模型数据的初始化已经采取懒加载的方式(每一个cell对应的frame模型数据只加载一次)


/**

 *  在这个方法中设置子控件的frame和显示数据

 */

- (void)setStatusFrame:(StatusFrame *)statusFrame

{

    _statusFrame = statusFrame;

    

    // 1.设置数据

    [self settingData];

    

    // 2.设置frame

    [self settingFrame];

}


demo下载地址: http://download.csdn.net/detail/linwenbang/8618345


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值