UITableView使用<1>之自定义UITableViewCell

本文详细介绍了如何自定义UITableViewCell,包括使用Xib和纯代码两种方式,以及如何使用纯代码实现不同内容结构和高度变化的cell。还提供了一个实例,通过创建数据模型类、Frame模型类和自定义Cell类来实现复杂cell布局。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于UITableViewCell,系统自身提供了几种样式:

  • UITableViewCellStyleDefault, // Simple cell with text label and optional image view
  • UITableViewCellStyleValue1, // Left aligned label on left and right aligned label on right with blue text
  • UITableViewCellStyleValue2, // Right aligned label on left with blue text and left aligned label on right
  • UITableViewCellStyleSubtitle // Left aligned label on top and left aligned label on bottom with gray text (Used in iPod).

当然,系统提供的这几种样式远无法满足我们的开发所需,所以我们需要自定义我们的UITableViewCell,这里提供两种方式来实现我们的目的:

一.利用Xib自定义UITableViewCell
这种方法适用于每个cell的内容结构、高度是一致的情况。

步骤:

  1. 现建一个*.xib文件
  2. 拽一个需要自定义的控件(比如要自定义UITableViewCell,则拽一个UITableViewCell),设置该cell的identifier,摆放其他自控件
  3. 新建一个类:类名要和*.xib文件名一致
  4. *.xib文件中自控件连线之前,需要将*.xib文件的根节点修改为刚刚新建的类名

代码如下:SSquestionCell.h*.m文件不变

在控制器中使用我们用Xib实现的自定义UITableViewCell时,要加载我们的Xib文件来创建cell。如下:

#import "SSquestionCell.h"
static NSString* const ID=@"cell";
    SSquestionCell* cell=[tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        //从xib加载自定义视图
        cell=[[[NSBundle mainBundle] loadNibNamed:@"SSquestionCell" owner:nil options:nil] lastObject];
    }

二.纯代码实现

1.注意:

  • 改变Cell行高有两种方法:改变属性self.tableView.rowHeight=100和通过代理方法:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 200;
}
  • -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    方法要早于
    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath调用

  • 只要有数据模型,便可计算出Cell中各控件的Frame

2.用代码实现自定义UITableViewCell可以分为两种情况:

<1>每个`Cell`的内容结构相同,也就是每个`Cell`的高度是一致的:这种情况使用Xib比较容易,如果使用代码的话,类似于使用纯代码自定义`UICollectionViewCell`,可以参考我之前写的[ UICollectionView学习<2>之UICollectionViewCell的自定义](http://blog.youkuaiyun.com/weichuang_1/article/details/48318019),这里就不再累赘了。

<2>这种情况比较复杂,不适合使用Xib来完成(典型的像新浪微博首页、腾讯的QQ空间):每个cell的内容结构可能不一样(有的子控件可能没有,相同的字控件可能尺寸不一致)、每个cell的高度即rowHeight不一致。这样的话我们要使用纯代码实现,我这里提供一种思路:
  1. 创建一个数据模型类:该类提供将字典转化为模型对象的方法
  2. 创建一个Frame模型类:向该类传入一个”步骤1”所创建的数据模型对象(因为只有知道数据,才能算出各个控件的Frame),该类用来保存每个字空间的Frame模型和Cell的高度数据。在数据模型的setter方法中计算各个子控件的Frame并赋值。
  3. 创建一个继承自UITableViewCell的自定义Cell类:向该类传递一个”步骤2”所创建的Frame模型对象,该类负责添加需要在Cell中显示的子控件,并且向外提供一个类方法来创建自定义的Cell。在Frame模型的setter方法中来设置子控件的数据和frame。
  4. 在控制器中定义一个Frame模型对象类型的数据数组(即数组的每一个元素是每一个Cell的Frame模型对象),在该数据数组的懒加载中从数据源获取数据来创建数据数组对象。然后实现UITableView的代理方法来展示我们想要的效果。

    代码(别人的代码)如下:

    步骤一:

#import <Foundation/Foundation.h>

@interface NJWeibo : NSObject
@property (nonatomic, copy) NSString *text; // 内容
@property (nonatomic, copy) NSString *icon; // 头像
@property (nonatomic, copy) NSString *name; // 昵称
@property (nonatomic, copy) NSString *picture; // 配图
@property (nonatomic, assign) BOOL vip;

- (id)initWithDict:(NSDictionary *)dict;
+ (id)weiboWithDict:(NSDictionary *)dict;
@end
#import "NJWeibo.h"

@implementation NJWeibo

- (id)initWithDict:(NSDictionary *)dict
{
    if (self = [super init]) {
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

+ (id)weiboWithDict:(NSDictionary *)dict
{
    return [[self alloc] initWithDict:dict];
}

@end

步骤二:

#import <Foundation/Foundation.h>
@class NJWeibo;
@interface NJWeiboFrame : NSObject

@property (nonatomic, assign) CGRect iconF;

@property (nonatomic, assign) CGRect nameF;

@property (nonatomic, assign) CGRect vipF;

@property (nonatomic, assign) CGRect introF;

@property (nonatomic, assign) CGRect pictrueF;

@property (nonatomic, assign) CGFloat cellHeight;


@property (nonatomic, strong) NJWeibo *weibo;
@end
#import "NJWeiboFrame.h"
#import "NJWeibo.h"
#define NJNameFont [UIFont systemFontOfSize:15]
#define NJTextFont [UIFont systemFontOfSize:16]


@implementation NJWeiboFrame


- (void)setWeibo:(NJWeibo *)weibo
{
    _weibo = weibo;

    // 间隙
    CGFloat padding = 10;

    // 设置头像的frame
    CGFloat iconViewX = padding;
    CGFloat iconViewY = padding;
    CGFloat iconViewW = 30;
    CGFloat iconViewH = 30;
    self.iconF = CGRectMake(iconViewX, iconViewY, iconViewW, iconViewH);

    // 设置昵称的frame
    // 昵称的x = 头像最大的x + 间隙
    CGFloat nameLabelX = CGRectGetMaxX(self.iconF) + padding;
    // 计算文字的宽高
    CGSize nameSize = [self sizeWithString:_weibo.name font:NJNameFont maxSize:CGSizeMake(MAXFLOAT, MAXFLOAT)];

    CGFloat nameLabelH = nameSize.height;
    CGFloat nameLabelW = nameSize.width;
    CGFloat nameLabelY = iconViewY + (iconViewH - nameLabelH) * 0.5;
   self.nameF = CGRectMake(nameLabelX, nameLabelY, nameLabelW, nameLabelH);

    // 设置vip的frame
    CGFloat vipViewX = CGRectGetMaxX(self.nameF) + padding;
    CGFloat vipViewY = nameLabelY;
    CGFloat vipViewW = 14;
    CGFloat vipViewH = 14;
    self.vipF = CGRectMake(vipViewX, vipViewY, vipViewW, vipViewH);

    // 设置正文的frame
    CGFloat introLabelX = iconViewX;
    CGFloat introLabelY = CGRectGetMaxY(self.iconF) + padding;
    CGSize textSize =  [self sizeWithString:_weibo.text font:NJTextFont maxSize:CGSizeMake(300, MAXFLOAT)];

    CGFloat introLabelW = textSize.width;
    CGFloat introLabelH = textSize.height;

    self.introF = CGRectMake(introLabelX, introLabelY, introLabelW, introLabelH);

    // 设置配图的frame
    CGFloat cellHeight = 0;
    if (_weibo.picture) {// 有配图
        CGFloat pictureViewX = iconViewX;
        CGFloat pictureViewY = CGRectGetMaxY(self.introF) + padding;
        CGFloat pictureViewW = 100;
        CGFloat pictureViewH = 100;
        self.pictrueF = CGRectMake(pictureViewX, pictureViewY, pictureViewW, pictureViewH);

        // 计算行高
        self.cellHeight = CGRectGetMaxY(self.pictrueF) + padding;
    }else
    {
        // 没有配图情况下的行高
        self.cellHeight = CGRectGetMaxY(self.introF) + padding;
    }

}

/**
 *  计算文本的宽高
 *
 *  @param str     需要计算的文本
 *  @param font    文本显示的字体
 *  @param maxSize 文本显示的范围
 *
 *  @return 文本占用的真实宽高
 */
- (CGSize)sizeWithString:(NSString *)str font:(UIFont *)font maxSize:(CGSize)maxSize
{
    NSDictionary *dict = @{NSFontAttributeName : font};
    // 如果将来计算的文字的范围超出了指定的范围,返回的就是指定的范围
    // 如果将来计算的文字的范围小于指定的范围, 返回的就是真实的范围
    CGSize size =  [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    return size;
}
@end

步骤三:

#import <UIKit/UIKit.h>
@class NJWeiboFrame;

@interface NJWeiboCell : UITableViewCell
/**
 *  接收外界传入的模型
 */
//@property (nonatomic, strong) NJWeibo *weibo;

@property (nonatomic, strong) NJWeiboFrame *weiboFrame;

+ (instancetype)cellWithTableView:(UITableView *)tableView;
@end
#import "NJWeiboCell.h"
#import "NJWeibo.h"
#import "NJWeiboFrame.h"

#define NJNameFont [UIFont systemFontOfSize:15]
#define NJTextFont [UIFont systemFontOfSize:16]

@interface NJWeiboCell ()
/**
 *  头像
 */
@property (nonatomic, weak) UIImageView *iconView;
/**
 *  vip
 */
@property (nonatomic, weak) UIImageView *vipView;
/**
 *  配图
 */
@property (nonatomic, weak) UIImageView *pictureView;
/**
 *  昵称
 */
@property (nonatomic, weak) UILabel *nameLabel;
/**
 *  正文
 */
@property (nonatomic, weak) UILabel *introLabel;
@end

@implementation NJWeiboCell

+ (instancetype)cellWithTableView:(UITableView *)tableView
{
    // NSLog(@"cellForRowAtIndexPath");
    static NSString *identifier = @"status";
    // 1.缓存中取
    NJWeiboCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    // 2.创建
    if (cell == nil) {
        cell = [[NJWeiboCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    return cell;
}


/**
 *  构造方法(在初始化对象的时候会调用)
 *  一般在这个方法中添加需要显示的子控件
 */
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // 让自定义Cell和系统的cell一样, 一创建出来就拥有一些子控件提供给我们使用
        // 1.创建头像
        UIImageView *iconView = [[UIImageView alloc] init];
        [self.contentView addSubview:iconView];
        self.iconView = iconView;

        // 2.创建昵称
        UILabel *nameLabel = [[UILabel alloc] init];
        nameLabel.font = NJNameFont;
        // nameLabel.backgroundColor = [UIColor redColor];
        [self.contentView addSubview:nameLabel];
        self.nameLabel = nameLabel;

        // 3.创建vip
        UIImageView *vipView = [[UIImageView alloc] init];
        vipView.image = [UIImage imageNamed:@"vip"];
        [self.contentView addSubview:vipView];
        self.vipView = vipView;

        // 4.创建正文
        UILabel *introLabel = [[UILabel alloc] init];
        introLabel.font = NJTextFont;
        introLabel.numberOfLines = 0;
        // introLabel.backgroundColor = [UIColor greenColor];
        [self.contentView addSubview:introLabel];
        self.introLabel = introLabel;

        // 5.创建配图
        UIImageView *pictureView = [[UIImageView alloc] init];
        [self.contentView addSubview:pictureView];
        self.pictureView = pictureView;

    }
    return self;
}


- (void)setWeiboFrame:(NJWeiboFrame *)weiboFrame
{
    _weiboFrame = weiboFrame;

    // 1.给子控件赋值数据
    [self settingData];
    // 2.设置frame
    [self settingFrame];
}

- (void)settingData
{
    NJWeibo *weibo = self.weiboFrame.weibo;

    // 设置头像
    self.iconView.image = [UIImage imageNamed:weibo.icon];
    // 设置昵称
    self.nameLabel.text = weibo.name;
    // 设置vip
    if (weibo.vip) {
        self.vipView.hidden = NO;
        self.nameLabel.textColor = [UIColor redColor];
    }else
    {
        self.vipView.hidden = YES;
        self.nameLabel.textColor = [UIColor blackColor];
    }
    // 设置内容
    self.introLabel.text = weibo.text;

    // 设置配图
    if (weibo.picture) {// 有配图
        self.pictureView.image = [UIImage imageNamed:weibo.picture];
        self.pictureView.hidden = NO;
    }else
    {
        self.pictureView.hidden = YES;
    }
}
- (void)settingFrame
{
       self.iconView.frame = self.weiboFrame.iconF;
       self.nameLabel.frame = self.weiboFrame.nameF;
       self.vipView.frame = self.weiboFrame.vipF;
       self.introLabel.frame = self.weiboFrame.introF;

    if (self.weiboFrame.weibo.picture) {// 有配图
        self.pictureView.frame = self.weiboFrame.pictrueF;
    }
}


- (CGSize)sizeWithString:(NSString *)str font:(UIFont *)font maxSize:(CGSize)maxSize
{
    NSDictionary *dict = @{NSFontAttributeName : font};
    CGSize size =  [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    return size;
}

@end

步骤四:

#import <UIKit/UIKit.h>

@interface NJViewController : UITableViewController

@end
#import "NJViewController.h"
#import "NJWeibo.h"
#import "NJWeiboCell.h"
#import "NJWeiboFrame.h"

@interface NJViewController ()
@property (nonatomic, strong) NSArray *statusFrames;
@end

@implementation NJViewController

#pragma mark - 数据源方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.statusFrames.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NJWeiboCell *cell = [NJWeiboCell cellWithTableView:tableView];
    // 3.设置数据
   cell.weiboFrame = self.statusFrames[indexPath.row];

    // 4.返回
    return cell;
}
#pragma mark - 懒加载
- (NSArray *)statusFrames
{
    if (_statusFrames == nil) {
        NSString *fullPath = [[NSBundle mainBundle] pathForResource:@"statuses.plist" ofType:nil];
        NSArray *dictArray = [NSArray arrayWithContentsOfFile:fullPath];
        NSMutableArray *models = [NSMutableArray arrayWithCapacity:dictArray.count];
        for (NSDictionary *dict in dictArray) {
            // 创建模型
            NJWeibo *weibo = [NJWeibo weiboWithDict:dict];
            // 根据模型数据创建frame模型
            NJWeiboFrame *wbF = [[NJWeiboFrame alloc] init];
            wbF.weibo = weibo;

            [models addObject:wbF];
        }
        self.statusFrames = [models copy];
    }
    return _statusFrames;
}

#pragma mark - 代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // NSLog(@"heightForRowAtIndexPath");
    // 取出对应航的frame模型
    NJWeiboFrame *wbF = self.statusFrames[indexPath.row];
    NSLog(@"height = %f", wbF.cellHeight);
    return wbF.cellHeight;
}

- (BOOL) prefersStatusBarHidden
{
    return YES;
}
@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值