UITableView 高级(动态cell高度 自定义cell)

UITableView 高级 

 

    自定义cell

    1.创建一个继承于UITableViewCell的子类

    2.根据展示的内容, 选择合适的控件, 并写属性

    3.重写cell的初始化方法, 在方法内部, 创建控件

    4.使用cell

PersonCell.m
#import <UIKit/UIKit.h>
@interface PersonCell : UITableViewCell
//注: 不要和UITableViewCell的属性重名
@property (nonatomic, retain) UIImageView *photoView;
@property (nonatomic, retain) UILabel *nameLabel, *genderLabel, *signatureLabel;
@end
PersonCell.m
#import "PersonCell.h"
#define kMargin 10
#define kImageSize 80
#define KNameWidth 150
#define KLabelHeight 35
#define KScreenWidth [UIScreen mainScreen].bounds.size.width
@implementation PersonCell
- (void)dealloc {
    [_photoView release];
    [_nameLabel release];
    [_genderLabel release];
    [_signatureLabel release];
    [super dealloc];
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
         头像
        self.photoView = [[UIImageView alloc] initWithFrame:CGRectMake(kMargin, kMargin, kImageSize, kImageSize)];
        //圆角的半径
        self.photoView.layer.cornerRadius = 40;
        self.photoView.clipsToBounds = YES;
//        self.photoView.layer.masksToBounds = YES;
        self.photoView.layer.borderWidth = 2;
        self.photoView.layer.borderColor = [UIColor colorWithRed:0.645 green:1.000 blue:0.970 alpha:1.000].CGColor;
        [self.contentView addSubview:_photoView];
        [_photoView release];
        
        姓名
        self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(kMargin * 2 + kImageSize, kMargin, KNameWidth, KLabelHeight)];
//        self.nameLabel.backgroundColor = [UIColor redColor];
        [self.contentView addSubview:_nameLabel];
        [self.nameLabel release];
        
        CGRect rect = CGRectMake(10, 10, 50, 50);
        获取矩形区域的宽度
        CGRectGetWidth(rect);
        获取矩形区域的高度
        CGRectGetHeight(rect);
        获取矩形区域的最小的X值
        CGRectGetMinX(rect);
        获取矩形区域的中间的X值
        CGRectGetMidX(rect);
        获取矩形区域的最大的X值
        CGRectGetMaxX(rect);
        //性别
        self.genderLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.nameLabel.frame) + kMargin, kMargin,KScreenWidth - kMargin * 2 - CGRectGetMaxX(self.nameLabel.frame) , KLabelHeight)];
//        self.genderLabel.backgroundColor = [UIColor greenColor];
        [self.contentView addSubview:_genderLabel];
        [self.genderLabel release];
        
        //个性签名
        self.signatureLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.nameLabel.frame), CGRectGetMaxY(self.nameLabel.frame) + kMargin, KScreenWidth - 2 * kMargin - CGRectGetMaxX(self.photoView.frame), KLabelHeight)];
        self.signatureLabel.font = [UIFont systemFontOfSize:13];
        self.signatureLabel.numberOfLines = 0;
//        self.signatureLabel.backgroundColor = [UIColor blueColor];
        [self.contentView addSubview:_signatureLabel];
        [self.signatureLabel release];
        
    }
    return self;
}

   

多种cell的混合使用

    1.根据需求不同, 返回不同的cell

    2.必须保证cell的重用标志是不同的

UITableViewCell.h
#import <UIKit/UIKit.h>
@interface MessageCell : UITableViewCell
@property (nonatomic, retain) UIImageView *photoView;
@property (nonatomic, retain) UILabel *chatLabel;
@end
UITableViewCell.m
#import "MessageCell.h"

#define KImageSize 80
#define kMargin 10
#define KScreenWidth [UIScreen mainScreen].bounds.size.width

@implementation MessageCell

- (void)dealloc {
    [_photoView release];
    [_chatLabel release];
    [super dealloc];
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.photoView = [[UIImageView alloc] initWithFrame:CGRectMake(KScreenWidth - KImageSize - kMargin , kMargin, KImageSize, KImageSize)];
        self.photoView.layer.cornerRadius = 40;
        self.photoView.clipsToBounds = YES;
        self.photoView.layer.borderWidth = 2;
        self.photoView.layer.borderColor = [UIColor colorWithRed:0.645 green:1.000 blue:0.970 alpha:1.000].CGColor;
        [self.contentView addSubview:_photoView];
        [_photoView release];
        
        self.chatLabel = [[UILabel alloc] initWithFrame:CGRectMake(kMargin, kMargin, KScreenWidth - 3 * kMargin - KImageSize, KImageSize)];
        self.chatLabel.numberOfLines = 0;
        self.chatLabel.backgroundColor = [UIColor colorWithRed:0.789 green:1.000 blue:0.970 alpha:1.000];
        self.chatLabel.layer.borderWidth = 1;
        [self.contentView addSubview:_chatLabel];
        [_chatLabel release];           
    }
    return  self;
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    // Return the number of sections.
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row % 2 == 0) {
        static NSString *string = @"OK";
        PersonCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (cell == nil) {
            cell = [[PersonCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:string];
        }
        cell.photoView.image = [UIImage imageNamed:@"image.jpg"];
        cell.nameLabel.text = @" 美眉";
        cell.genderLabel.text = @"";
        cell.signatureLabel.text = @"个性签名: 当你对成功的渴望足以与呼吸的欲望相媲美时,你就会成功!";
        return cell;

    } else {
    static NSString *string = @"Hello";
    MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (cell == nil) {
        cell = [[MessageCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:string];
    }
    cell.photoView.image = [UIImage imageNamed:@"other.jpg"];
    cell.chatLabel.text = @"    让人迷茫的原因只有一个,那就是本该拼搏的年纪,想的太多,做的太少。";
    return cell;
    }
}

    动态cell高度

    1.展示内容的控件的高度修改

    a. numberOfLines

    b. boundingRectWithSize

    2.修改cell的高度

 HomeTableViewCell.h
#import <UIKit/UIKit.h>
@class Joke;
@interface HomeTableViewCell : UITableViewCell
@property (nonatomic, retain) UILabel *nameLabel, *contentLabel;
自定义cell的优化方法, 对cell上展示的内容, 写一个方法封装起来, 方便赋值
- (void)showContent:(Joke *)joke;
+ (CGFloat)calculateRowHeight:(Joke *)joke;
@end
HomeTableViewCell.m
#import "HomeTableViewCell.h"
#import "Joke.h"
@implementation HomeTableViewCell
- (void)dealloc {
    [_nameLabel release];
    [_contentLabel release];
    [super dealloc];
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        //姓名
        self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 355, 20)];
//        self.nameLabel.backgroundColor = [UIColor colorWithRed:0.658 green:1.000 blue:0.975 alpha:1.000];
        [self.contentView addSubview:_nameLabel];
        [_nameLabel release];
        
        //内容
        self.contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 40, 355, 20)];
        self.contentLabel.backgroundColor = [UIColor colorWithRed:1.000 green:0.988 blue:0.889 alpha:1.000];
        self.contentLabel.numberOfLines = 0;
        [self.contentView addSubview:_contentLabel];
        [_contentLabel release];
        
    }
    return self;
}

- (void)showContent:(Joke *)joke {
    self.nameLabel.text = joke.name;
    self.contentLabel.text = joke.content;
    
    通过内容, 计算高度
    参数1: 展示内容的容器大小(CGSize)
    参数2: 计算方式(行高 + 间距)(NSStringDrawingOptions)
    参数3: 文字样式(文字大小)(NSDictionary *)
    参数4: 传递参数使用(NSStringDrawingContext *)
    NSDictionary *dic = @{NSFontAttributeName: [UIFont systemFontOfSize:17]};
    CGRect rect = [joke.content boundingRectWithSize:CGSizeMake(355, 0) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:dic context:nil];
    CGRect frame = self.contentLabel.frame;
    frame.size.height = rect.size.height;
    self.contentLabel.frame = frame;
    
}

+ (CGFloat)calculateRowHeight:(Joke *)joke {
    NSDictionary *dic = @{NSFontAttributeName: [UIFont systemFontOfSize:17]};
    CGRect rect = [joke.content boundingRectWithSize:CGSizeMake(355, 0) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:dic context:nil];
    return rect.size.height + 20 + 30;
}

@end
Joke.h
#import <Foundation/Foundation.h>

@interface Joke : NSObject

@property (nonatomic, retain) NSString *name, *content;

- (instancetype)initWithName:(NSString *)namae content:(NSString *)content;
+ (instancetype)jokeWithName:(NSString *)namae content:(NSString *)content;

@end
Joke.m
#import "Joke.h"
@implementation Joke
- (void)dealloc {
    [_name release];
    [_content release];
    [super dealloc];
}

- (instancetype)initWithName:(NSString *)namae content:(NSString *)content {
    if (self = [super init]) {
        self.name = namae;
        self.content = content;
    }
    return self;
}
+ (instancetype)jokeWithName:(NSString *)namae content:(NSString *)content {
    return [[Joke alloc] initWithName:namae content:content];
}

@end
- (void)creatData {
    Joke *joke1 = [Joke jokeWithName:@"忠忠" content:@"1、毕业后才知道校园恋爱是最纯洁的;2、毕业后才知道学习是最重要的;3、毕业后才知道校园生活是最幸福的;4、毕业后才知道宿舍生活是最好的;5、毕业后才知道食堂的饭菜是最便宜的;6、毕业后才知道上学是最美妙的事。7、毕业后才知道学生花钱最大手大脚......"];
    Joke *joke2 = [Joke jokeWithName:@"老王" content:@"一年奔波,尘缘遇了谁;一句珍重,天涯别了谁;一点灵犀,凭栏忆了谁;一种相思,闲愁予了谁;一江明月,豪情酬了谁;一场冬雪,烟波忘了谁;一壶浊酒,相逢醉了谁;一世浮生,轻狂撩了谁;一封短信,才情念了谁;一番思量,谁是谁的谁 ;一枚围脖,转发回复谁....."];
    Joke *joke3 = [Joke jokeWithName:@"蹦蹦" content:@"人与人间的信任,就像是纸片,一旦破损,就不会再回到原来的样子。"];
    Joke *joke4 = [Joke jokeWithName:@"小强" content:@"记者:说真的,你真的会给给孩子换尿布吗? 姚明:要不你躺下,我给你换一个!实话告诉你,我用一只脚就能给孩子换尿布,喂奶啥的,都行。 记者:我不信! 姚明:真的,连灯都不用开。 记者:不可能!你说怎么换? 姚明:一只脚把媳妇揣醒就得。"];
    Joke *joke5 = [Joke jokeWithName:@"广恩" content:@"一生只谈三次恋爱最好,一次懵懂,一次刻骨,一次一生。谈的太多会比较,无法确定;经历太多会麻木,不再相信爱情,行尸走肉,最后与不爱的人结婚,无法发自内心的爱对方,日常表现的应付,对方则抱怨你不够关心和不顾家,最后这失败的爱情,让你在遗憾和凑合中走完一生。"];
    Joke *joke6 = [Joke jokeWithName:@"歌星" content:@"我们常常看到的风景是:一个人总是仰望和羡慕着别人的幸福,一回头,却发现自己正被仰望和羡慕着。其实,每个人都是幸福的。只是,你的幸福,常常在别人眼里 。"];
    self.jokeArray = [@[joke1, joke2, joke3, joke4, joke5, joke6] mutableCopy];
  
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return self.jokeArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"cell";
    HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[HomeTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
//    cell.textLabel.text = @"Hello World!";
    Joke *joke = _jokeArray[indexPath.row];
    [cell showContent:joke];
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [HomeTableViewCell calculateRowHeight:self.jokeArray[indexPath.row]];
}

 

 

The one who wants to wear a crown must bear the weight!
原文地址:https://www.cnblogs.com/OrangesChen/p/4926192.html