iOS编程------自定义UITableViewCell / cell自适应高度

//
//  AppDelegate.h
//  UI11_UITableViewCustomCell_autoHeight
//
//  Created by l on 15/9/15.
//  Copyright (c) 2015年 . All rights reserved.
//

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;


@end






//
//  AppDelegate.m
//  UI11_UITableViewCustomCell_autoHeight
//
//  Created by l on 15/9/15.
//  Copyright (c) 2015年 . All rights reserved.
//

#import "AppDelegate.h"
#import "RootTableViewController.h"
@interface AppDelegate ()

@end

@implementation AppDelegate
- (void)dealloc{
    [_window release];
    [super dealloc];
 }

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    //--//
    RootTableViewController *rootVC = [[RootTableViewController alloc] init];
    UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:rootVC];
    self.window.rootViewController = navC;

    [navC release];
    [rootVC release];



    return YES;
}

@end



//



//
//  RootTableViewController.h
//  
//
//  Created by l on 15/9/15.
//
//

#import <UIKit/UIKit.h>

@interface RootTableViewController : UITableViewController

@end





//
//  RootTableViewController.m
//  
//
//  Created by l on 15/9/15.
//
//

#import "RootTableViewController.h"
#import "StudentCell.h"//导入自定义的单元格头文件
#import "Student.h"//导入student数据模型头文件
#import "StudentCell2.h"

@interface RootTableViewController ()
//创建一个数据容器,存放解析后的model
@property (nonatomic, retain) NSMutableArray *studentArray;//存放学生model


@end

@implementation RootTableViewController
- (void)dealloc{
    [_studentArray release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"联系人";

    //重点:解析数据 把 数据映射为数据模型, 放到controller 存放数据的模型容器中

    //1. plist 文件路径
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Students" ofType:@"plist"];

    //2.根据plist的根节点,创建响应的数据容器
    NSArray *sourceArray = [NSArray arrayWithContentsOfFile:filePath];

    //3.把 dictionary数据转换为 student对象

    //给controller的数据容器开辟空间
    self.studentArray = [NSMutableArray array];

    for (NSDictionary *dic in sourceArray) {
        Student *student = [[Student alloc] init];

//        student.icon = [dic objectForKey:@"icon"];

        //kvc赋值 用dic给student赋值
        [student setValuesForKeysWithDictionary:dic];

        [_studentArray addObject:student];


    }

//    NSLog(@"%@", _studentArray);




    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

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

#pragma mark - Table view data source
//区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [_studentArray count];
}

//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //先执行的该方法设置每行高度,然后才执行的加载单元格方法
    //因此,我们把获取单元格高度设置为类方法,因为此时还没创建单元格对象
    Student *student = _studentArray[indexPath.row];
    return [StudentCell cellHeightForStudent:student];
}

//加载单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    //同一个tableView中使用多个不同的单元格,需要根据加载的数据进行判断
    //是什么数据就采用哪种类型的单元格
    //思想:根据indexpath取到的数据进行判断

    //(1)获取数据
    Student *student = _studentArray[indexPath.row];

    //(2)判断
    if ([student.sex isEqualToString:@"女"]) {
        //如果是女生,则加载studentCell2单元格
        static NSString *resuerIndenfier = @"cell2";
        StudentCell2 *cell = [tableView dequeueReusableCellWithIdentifier:resuerIndenfier];
        if (cell == nil) {
            cell = [[[StudentCell2 alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:resuerIndenfier] autorelease];
        }
        cell.student = student;

        return cell;

    }else{


    static NSString *reuseIdentifier = @"cell";

    StudentCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];

    if (cell == nil) {

        cell = [[[StudentCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:reuseIdentifier] autorelease];
    }

    // Configure the cell...
    //给单元格 添加数据

    //1.取到对应的student
//    Student *student = _studentArray[indexPath.row];

    //2.给cell的model赋值
    cell.student = student;

    return cell;
}


}

@end











//
//  StudentCell.h
//  UI11_UITableViewCustomCell_autoHeight
//
//  Created by l on 15/9/15.
//  Copyright (c) 2015年 . All rights reserved.
//

#import <UIKit/UIKit.h>
/**
 *  该单元格为自定义单元格,有5个控件
 左边         右边

 图片视图      姓名
              性别
              手机号
              自我介绍
 */
@class Student;
@interface StudentCell : UITableViewCell
//view层,自定义内部控件

//个人图片
@property (nonatomic, retain, readonly) UIImageView *iconImageView;
//姓名
@property (nonatomic, retain, readonly) UILabel *nameLabel;
//性别
@property (nonatomic, retain, readonly) UILabel *genderLabel;
//手机号
@property (nonatomic, retain, readonly) UILabel *phoneNumberLabel;
//介绍
@property (nonatomic, retain, readonly) UILabel *introduceLabel;


//model层, 外部给cell数据

@property (nonatomic, retain) Student *student;

//单元格自适应高度
//核心思想:根据文本的不同绘制不同高度的矩形
//调用了string的实例方法 绘制矩形方法
//获取文本的高度
//类方法 获取文本的高度
+ (CGFloat)heightForString:(NSString *)string;

//单元格整体的高度
//整体高度 = 固定高度 + introduceLabel高度
+ (CGFloat)cellHeightForStudent:(Student *)student;



@end





//
//  StudentCell.m
//  UI11_UITableViewCustomCell_autoHeight
//
//  Created by l on 15/9/15.
//  Copyright (c) 2015年 . All rights reserved.
//

#import "StudentCell.h"
#import "Student.h"

//宏定义
#define KLeft 10;

#define KTop 10

#define KHorizonSpacing 10 //水平间距

#define KVerticalSpacing 10 //竖直间距




@implementation StudentCell
- (void)dealloc{
    [_iconImageView release];
    [_nameLabel release];
    [_genderLabel release];
    [_phoneNumberLabel release];
    [_introduceLabel release];
    [_student release];
    [super dealloc];
}

//初始化
//重写cell的init方法,添加内部控件
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{

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

    if (self) {

        //添加内部控件
        CGFloat totalWidth = [UIScreen mainScreen].bounds.size.width; //总宽度
        CGFloat labelHeight = 30; //label高度

        //iconImageView
        CGFloat iconX = KLeft;
        CGFloat iconY = KTop;
        CGFloat iconWidth = 150;
        CGFloat iconHeight = 225;

        _iconImageView = [[UIImageView alloc] initWithFrame:(CGRectMake(iconX, iconY, iconWidth, iconHeight))];

        _iconImageView.backgroundColor = [UIColor yellowColor];
//        _iconImageView.alpha = 0.5;

        //添加到cell contentView上
        [self.contentView addSubview:_iconImageView];

        //----------------------------------------------/

        //nameLabel
        CGFloat nameX = iconX + iconWidth + KHorizonSpacing;
        CGFloat nameY = KTop;
        CGFloat nameWidth = totalWidth - nameX - KLeft;
        CGFloat nameHeight = labelHeight;

        _nameLabel = [[UILabel alloc] initWithFrame:(CGRectMake(nameX, nameY, nameWidth, nameHeight))];

        _nameLabel.backgroundColor = [UIColor cyanColor];
        _nameLabel.alpha = 0.5;

        _nameLabel.font = [UIFont systemFontOfSize:18];

        [self.contentView addSubview:_nameLabel];


        //----------------------------------------------/

        //genderLabel
        CGFloat genderX = nameX;
        CGFloat genderY = nameY + nameHeight + KVerticalSpacing;
        CGFloat genderWidth = nameWidth;
        CGFloat genderHeight = labelHeight;


        _genderLabel = [[UILabel alloc] initWithFrame:(CGRectMake(genderX, genderY, genderWidth, genderHeight))];

        _genderLabel.backgroundColor = [UIColor cyanColor];
        _genderLabel.alpha = 0.5;

        _genderLabel.font = [UIFont systemFontOfSize:18];

        [self.contentView addSubview:_genderLabel];


        //-----------------------------------------------/

       //phoneNumberLabel
        CGFloat phoneX = genderX;
        CGFloat phoneY = genderY + genderHeight + KVerticalSpacing;
        CGFloat phoneWidth = genderWidth;
        CGFloat phoneHeight = labelHeight;

        _phoneNumberLabel = [[UILabel alloc] initWithFrame:(CGRectMake(phoneX, phoneY, phoneWidth, phoneHeight))];

        _phoneNumberLabel.backgroundColor = [UIColor cyanColor];
        _phoneNumberLabel.alpha = 0.5;

        _phoneNumberLabel.font = [UIFont systemFontOfSize:18];

        [self.contentView addSubview:_phoneNumberLabel];

        //--------------------------------------------/

        //introduceLabel
        CGFloat introX = phoneX;
        CGFloat introY = phoneY + phoneHeight + KVerticalSpacing;
        CGFloat introWidth = phoneWidth;
        CGFloat introHeight = 2 * labelHeight;

        _introduceLabel = [[UILabel alloc] initWithFrame:(CGRectMake(introX, introY, introWidth, introHeight))];

        _introduceLabel.backgroundColor = [UIColor cyanColor];
        _introduceLabel.alpha = 0.5;

        _introduceLabel.font = [UIFont systemFontOfSize:18];

        _introduceLabel.numberOfLines = 0;//自动换行

        [self.contentView addSubview:_introduceLabel];

    }

    return self;
}

//赋值,重写model 的set方法

- (void)setStudent:(Student *)student{

    if (_student != student) {
        [_student release];
        _student = [student retain];

        //当外界给cell的model赋值时,给内部控件赋值
        _iconImageView.image = [UIImage imageNamed:student.icon];
        _nameLabel.text = student.name;
        _genderLabel.text = student.sex;
        _phoneNumberLabel.text = student.phoneNumber;
        _introduceLabel.text = student.introduce;

        //自适应高度
        //获取到student,根据student的introduce 文本调整高度

        //调整introduceLabel的高度
        CGRect recIntroduce = _introduceLabel.frame;

        recIntroduce = CGRectMake(recIntroduce.origin.x, recIntroduce.origin.y, recIntroduce.size.width, [StudentCell heightForString:student.introduce]);

        _introduceLabel.frame = recIntroduce;


        //调整cell的高度
        CGRect originFrame = self.frame;

        CGFloat height = [StudentCell cellHeightForStudent:student];

        originFrame = CGRectMake(originFrame.origin.x, originFrame.origin.y, originFrame.size.width,height);

        self.frame = originFrame;

    }
}

/*
 计算一段文本在限定宽高内所占矩形大小
 - (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context

 */
#pragma mark-- 自适应高度
//获取文本的高度
+ (CGFloat)heightForString:(NSString *)string{

    //size绘制矩形的最大宽度 最大高度
    //options绘制文本时的基线
    //attributes 绘制时使用的字体的属性
    //context 绘制上下文 ,通常给nil

    //注意: 1.size 的宽度一定要和负责文字显示的空间宽度相等 2.字体属性 也要相等

    //1.字体属性
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:18], NSFontAttributeName, nil];

    //2.指定绘制矩形的最大宽度高度
    CGFloat width = [UIScreen mainScreen].bounds.size.width - 150  - KHorizonSpacing - 2 * KLeft;
    CGSize size = CGSizeMake(width, 10000);

    //3.绘制矩形
    CGRect bounding = [string boundingRectWithSize:size options:(NSStringDrawingUsesLineFragmentOrigin) attributes:attributes context:nil];

    //4.返回高度
    return bounding.size.height;

}

//单元格整体的高度
+ (CGFloat)cellHeightForStudent:(Student *)student{

    //单元格整体高度 = 文本高度 + 固定高度
    //1.获取文本高度
    CGFloat stringHeight = [self heightForString:student.introduce];

    //2.整体高度
    CGFloat cellHeight = 2 * KTop + 3 * (KVerticalSpacing + 30) + stringHeight;

    //3.判断整体高度和最小高度
    CGFloat miniCellHeight = 2 * KTop + 225;

    //如果整体高度大于最小高度 返回整体高度,否则返回最小高度
    return cellHeight > miniCellHeight ? cellHeight : miniCellHeight;


}

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
















//
//  StudentCell2.h
//  UI11_UITableViewCustomCell_autoHeight
//
//  Created by l on 15/9/15.
//  Copyright (c) 2015年 . All rights reserved.
//

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

@interface StudentCell2 : UITableViewCell

//view层,自定义内部控件

//个人图片
@property (nonatomic, retain, readonly) UIImageView *iconImageView;
//姓名
@property (nonatomic, retain, readonly) UILabel *nameLabel;
//性别
@property (nonatomic, retain, readonly) UILabel *genderLabel;
//手机号
@property (nonatomic, retain, readonly) UILabel *phoneNumberLabel;
//介绍
@property (nonatomic, retain, readonly) UILabel *introduceLabel;


//model层, 外部给cell数据

@property (nonatomic, retain) Student *student;

@end






//
//  StudentCell2.m
//  UI11_UITableViewCustomCell_autoHeight
//
//  Created by l on 15/9/15.
//  Copyright (c) 2015年 . All rights reserved.
//

#import "StudentCell2.h"
#import "Student.h"

#define KLeft 10;

#define KTop 10

#define KHorizonSpacing 10 //水平间距

#define KVerticalSpacing 10 //竖直间距


@implementation StudentCell2
- (void)dealloc{
    [_iconImageView release];
    [_nameLabel release];
    [_genderLabel release];
    [_phoneNumberLabel release];
    [_introduceLabel release];
    [_student release];
    [super dealloc];
}


//重写cell的init方法,添加内部控件
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{

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

    if (self) {

        //添加内部控件
        CGFloat totalWidth = [UIScreen mainScreen].bounds.size.width; //总宽度
        CGFloat labelHeight = 30; //label高度

        //iconImageView

        CGFloat iconWidth = 150;

        CGFloat iconHeight = 225;

//        CGFloat iconX = totalWidth - KLeft - iconWidth;
        CGFloat iconX = totalWidth - iconWidth - KLeft;
        CGFloat iconY = KTop;

        _iconImageView = [[UIImageView alloc] initWithFrame:(CGRectMake(iconX, iconY, iconWidth, iconHeight))];

        _iconImageView.backgroundColor = [UIColor yellowColor];
        //        _iconImageView.alpha = 0.5;

        //添加到cell contentView上
        [self.contentView addSubview:_iconImageView];

        //----------------------------------------------/

        //nameLabel
        CGFloat nameX = KLeft;
        CGFloat nameY = KTop;
//        CGFloat nameWidth = totalWidth - iconWidth - 2 * KLeft - KHorizonSpacing;
        CGFloat nameWidth = totalWidth - iconWidth - KHorizonSpacing - 2 * KLeft;
        CGFloat nameHeight = labelHeight;

        _nameLabel = [[UILabel alloc] initWithFrame:(CGRectMake(nameX, nameY, nameWidth, nameHeight))];

        _nameLabel.backgroundColor = [UIColor cyanColor];
        _nameLabel.alpha = 0.5;

        _nameLabel.font = [UIFont systemFontOfSize:18];

        [self.contentView addSubview:_nameLabel];


        //----------------------------------------------/

        //genderLabel
        CGFloat genderX = nameX;
        CGFloat genderY = nameY + nameHeight + KVerticalSpacing;
        CGFloat genderWidth = nameWidth;
        CGFloat genderHeight = labelHeight;


        _genderLabel = [[UILabel alloc] initWithFrame:(CGRectMake(genderX, genderY, genderWidth, genderHeight))];

        _genderLabel.backgroundColor = [UIColor cyanColor];
        _genderLabel.alpha = 0.5;

        _genderLabel.font = [UIFont systemFontOfSize:18];

        [self.contentView addSubview:_genderLabel];


        //-----------------------------------------------/

        //phoneNumberLabel
        CGFloat phoneX = genderX;
        CGFloat phoneY = genderY + genderHeight + KVerticalSpacing;
        CGFloat phoneWidth = genderWidth;
        CGFloat phoneHeight = labelHeight;

        _phoneNumberLabel = [[UILabel alloc] initWithFrame:(CGRectMake(phoneX, phoneY, phoneWidth, phoneHeight))];

        _phoneNumberLabel.backgroundColor = [UIColor cyanColor];
        _phoneNumberLabel.alpha = 0.5;

        _phoneNumberLabel.font = [UIFont systemFontOfSize:18];

        [self.contentView addSubview:_phoneNumberLabel];

        //--------------------------------------------/

        //introduceLabel
        CGFloat introX = phoneX;
        CGFloat introY = phoneY + phoneHeight + KVerticalSpacing;
        CGFloat introWidth = phoneWidth;
        CGFloat introHeight = 4 * labelHeight;

        _introduceLabel = [[UILabel alloc] initWithFrame:(CGRectMake(introX, introY, introWidth, introHeight))];

        _introduceLabel.backgroundColor = [UIColor cyanColor];
        _introduceLabel.alpha = 0.5;

        _introduceLabel.font = [UIFont systemFontOfSize:18];

        _introduceLabel.numberOfLines = 0;//自动换行

        [self.contentView addSubview:_introduceLabel];

    }

    return self;
}

//赋值,重写model 的set方法

- (void)setStudent:(Student *)student{

    if (_student != student) {
        [_student release];
        _student = [student retain];

        //当外界给cell的model赋值时,给内部控件赋值
        _iconImageView.image = [UIImage imageNamed:student.icon];
        _nameLabel.text = student.name;
        _genderLabel.text = student.sex;
        _phoneNumberLabel.text = student.phoneNumber;
        _introduceLabel.text = student.introduce;

    }
}





- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end







/




//
//  Student.h
//  UI11_UITableViewCustomCell_autoHeight
//
//  Created by l on 15/9/15.
//  Copyright (c) 2015年 . All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Student : NSObject

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

@property (nonatomic, copy) NSString *name;

@property (nonatomic, copy) NSString *phoneNumber;

@property (nonatomic, copy) NSString *sex;

@property (nonatomic, copy) NSString *introduce;

@end






//
//  Student.m
//  UI11_UITableViewCustomCell_autoHeight
//
//  Created by l on 15/9/15.
//  Copyright (c) 2015年 . All rights reserved.
//

#import "Student.h"

@implementation Student
- (void)dealloc{
    [_icon release];
    [_name release];
    [_phoneNumber release];
    [_sex release];
    [_introduce release];
    [super dealloc];
}



@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值