Cell自适应高度及自定义cell混合使…

第一部分:UItableViewCellAdaptionForHeight
: cell的自适应高度
第二部分:CustomTableViewCell:自定义cell的混合使用(以简单通讯录为例)
=================cell的自适应高度====================
AppDelegate.m
#import "NewsController.h"
 self.window.rootViewController
=
[[[UINavigationController
alloc]initWithRootViewController:[NewsController
new]]autorelease];
本节所需素材下载:http://pan.baidu.com/s/1bnnwmmj
通讯录素材需要自己整理,涉及到个人隐私不给于提供!
——————————————————————————————
NewsController.m
#import "NewsCell.h"

#define kNewsCell @"news-cell"

#import "News.h"
@interface NewsController ()
@property(nonatomic,retain)NSMutableArray *dateSouce;
@end
@implementation NewsController

- (void)dealloc{

   
self.dateSouce = nil;

   
[super
dealloc];

}

- (void)viewDidLoad {

   
[super
viewDidLoad];

   
//配置导航条信息

   
[self
configureNavigationControllerBarConten];

 
 //注册

   
[self.tableView registerClass:[NewsCell class] forCellReuseIdentifier:kNewsCell];

//从Plist文件中读取文件

   
[self
readDataFromPlist];  
}
//从Plist文件中读取文件

- (void)readDataFromPlist{

   
//获取文件路径

   
NSString
*fielPath =
[[NSBundle mainBundle]pathForResource:@"NewsData.plist"
ofType:nil];

   
//从文件中读取数据,由于文件最外层是字典,所以使用字典接受读取的数据

NSDictionary
*dict =
[NSDictionary dictionaryWithContentsOfFile:fielPath];

//   
NSLog(@"%@",dict); 验证

   
NSArray
*array =
dict[@"news"];
//   
NSLog(@"%@",array);

 
  
   
self.dateSouce = [NSMutableArray arrayWithCapacity:0];
   
for (NSDictionary *d in array) {

       
//创建model对象

News
*news =
[[News
alloc]init];

//给news赋值

       
[news setValuesForKeysWithDictionary:d];

//把初始化完成的model对象放到数组中

[self.dateSouce addObject:news];

       
[news release];
   
}
//   
NSLog(@"%@",self.dateSouce); 
验证是否放到数组中
}
//配置导航条信息

- (void)configureNavigationControllerBarConten{

self.navigationController.navigationBar.barTintColor
= [UIColor orangeColor];

   
self.navigationItem.title = @"北京新闻";

}

-
(NSInteger)numberOfSectionsInTableView:(UITableView
*)tableView
{
//只需要一个区
   
return
1;

}


-
(NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
   
return
self.dateSouce.count;
}
-
(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {

   NewsCell *cell = [tableView
dequeueReusableCellWithIdentifier:kNewsCell
forIndexPath:indexPath];

   

    [cell
setValueByNews:self.dateSouce[indexPath.row]];
//选中cell的背景颜色

cell.selectedBackgroundView
= [[UIView alloc]initWithFrame:cell.frame];

   
cell.selectedBackgroundView.backgroundColor
= [UIColor greenColor];

   
//取消边框线

    [cell
setBackgroundView:[[UIView
alloc]init]];

cell.backgroundColor = [UIColor clearColor];

   

   
return
cell;

}
//返回行高 
此方法要比返回cell的方法先执行,所以在没有返回cell之,就在这里确定cell的高

-
(CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   
return
[NewsCell cellHeight:self.dateSouce[indexPath.row]];
}
—————————————————————————————————
创建自定义cell
NewsCell.m
@class
News;

@interface NewsCell : UITableViewCell
//写一个方法给cell上的控件赋值

- (void)setValueByNews :
(News
*)news;


//定义一个类方法返回cell的行高

//根据传进来的数据,计算当前cell的行高

+ (CGFloat)cellHeight : (News *)news;


@end
——————————————————————————————————
NewsCell.m
@interface NewsCell ()
@property(nonatomic,retain)UILabel *titleLabel;//标题
@property(nonatomic,retain)UILabel *summaryLabel;//新闻内容
@end
@implementation NewsCell

- (void)dealloc{

   
self.titleLabel = nil;

   
self.summaryLabel = nil;



   
[super
dealloc];

}



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

   
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {

[self.contentView addSubview:self.titleLabel];

       
[self.contentView
addSubview:self.summaryLabel];
   
}

   
return
self;

}


//懒加载方法
//titleLabel 10 10 300
30

- (UILabel *)titleLabel{

   
if (_titleLabel == nil) {

       
self.titleLabel = [[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 300, 30)]autorelease];

       
self.titleLabel.backgroundColor = [UIColor brownColor];

}

   
return
[[_titleLabel retain]autorelease];

}
//summaryLabe 10 50 300
50

- (UILabel *)summaryLabel{

   
if (_summaryLabel == nil) {

       
self.summaryLabel = [[[UILabel alloc]initWithFrame:CGRectMake(10, 50, 300, 50)]autorelease];
//       
self.summaryLabel.backgroundColor = [UIColor
yellowColor];

       
//设置文字大小

       
self.summaryLabel.font = [UIFont systemFontOfSize:17.0];

       
//根据内容换行

       
self.summaryLabel.numberOfLines = 0;
   
}

   
return
[[_summaryLabel retain]autorelease];

}
Cell自适应高度及自定义cell混合使…



 +
(CGFloat)summaryLabelheight :
(NSString
*)summary{
   
//参数解释
 
  1.绘制文本的限制
 
  2.设置文本高度的标准
 
  3.设置文字的属性(文字属性中字体的大小要和summaryLabel上设置的文字大小一致)
 
  4.文本上下文
nil
   
//设置文本内容的宽高

CGSize
contextSize =
CGSizeMake(300, 0);

   

   
//设置计算时文本的一些属性,比如:字体的大小

NSDictionary
*attributes =
@{NSFontAttributeName
: [UIFont systemFontOfSize:17.0]};

   
CGRect
summaryRect =
[summary boundingRectWithSize:contextSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes context:nil];

   
return
summaryRect.size.height;

}

//根据传进来的数据,计算当前cell的行高
+
(CGFloat)cellHeight : (News
*)news{
分析:
   
//   
return 不可变的高 + 可变的高

   
//不可变的 10 + 30 + 10 +
10

   
//可变的 summaryLabel
的高

   
//计算可变的
summary文本高度

   
CGFloat
summartHeight =
[self
summaryLabelheight:news.summary];
   
return
10 + 30 + 10 + 10 +
summartHeight;
}


//写一个方法给cell上的控件赋值

- (void)setValueByNews :
(News
*)news{

   
self.titleLabel.text = news.title;

   
self.summaryLabel.text = news.summary;

   

   
//赋值完成之后重新计算self.summaryLabel的大小

CGRect
summaryRect =
self.summaryLabel.frame;

   
//修改summaryRect的高

summaryRect.size.height = [[self class]summaryLabelheight:news.summary];

//将修改后的大小赋值给self.summaryLabel.frame

   
self.summaryLabel.frame =
summaryRect;
}
——————————————————————————————
创建一个model类继承自NSObject
News.h
@interface News : NSObject
@property(nonatomic,copy)NSString *title;
@property(nonatomic,copy)NSString *summary;
@end
——————————————————————————————
News.m
@implementation News

-(void)dealloc{

   
self.title = nil;

   
self.summary = nil;

   
[super
dealloc];

}
//安全机制,防止未取到key值对应的Value值造成Crash

- (void)setValue:(id)value
forUndefinedKey:(NSString *)key{

   
//可以什么也不写

}
@end
最终效果:
Cell自适应高度及自定义cell混合使…
——————————————————————————————
=================自定义cell的混合使用===============
AppDelegate.m
   
self.window.rootViewController
=
[[[UINavigationController
alloc]initWithRootViewController:[ContactTableViewController
new]]autorelease];
ContactTableViewController.m
#import
"Person.h"

#import "BoyCell.h"

#import "GirlCell.h"

#define kBoyCell @"boy-cell"

#define kGirlCell @"girl-cell"

@interface
ContactTableViewController
()
@property(nonatomic,retain)NSMutableDictionary
*dataSource;//存放所有联系人

@property(nonatomic,retain)NSMutableArray
*orderedKeys;//存放排好序的key
@end
@implementation
ContactTableViewController

- (void)dealloc{

self.dataSource
=
nil;

self.orderedKeys
=
nil;

[super
dealloc];

}

- (void)viewDidLoad
{

   
[super
viewDidLoad];
   
[self
costomBar];

//读取plist文件

   
[self
readDataFromPlist];

//cell重用新方法的使用步骤:第一步注册cell

//第一个参数:提供cell类

//第二个参数:提供cell"重用ID"

//注册boycell

[self.tableView
registerClass:[BoyCell
class]
forCellReuseIdentifier:kBoyCell];

//注册gielcell

[self.tableView
registerClass:[GirlCell
class]
forCellReuseIdentifier:kGirlCell];

//配置cell的行高

   
self.tableView.rowHeight
=
80.0;
}



- (void)costomBar{

self.navigationController.navigationBar.barTintColor
=
[UIColor
cyanColor];

   
self.navigationItem.title
=
@"联系人";
}


//从plist文件读取数据

- (void)readDataFromPlist{

//获取文件路径

NSString
*filePath =
[[NSBundle
mainBundle]pathForResource:@"Contacts.plist"
ofType:nil];

//取出文件中的内容

NSDictionary
*dict =
[NSDictionary
dictionaryWithContentsOfFile:filePath];

//   
NSLog(@"%@",dict);   验证

   
//初始化联系人字典

   
self.dataSource
=
[NSMutableDictionary
dictionaryWithCapacity:0];

   
for
(NSString
*key
in
dict) {

       
//取出字典中key值对应的数组
       
NSArray
*group =
dict[key];
       
//存放初始化的model数据模型Person对象

NSMutableArray
*mGroup =
[NSMutableArray
arrayWithCapacity:0];

for
(NSDictionary
*d
in
group) {

           
//使用字典初始化数据模型Person对象

Person
*p
= [[Person
alloc]init];

[p setValuesForKeysWithDictionary:d];

//将p添加到mGroup数组中

[mGroup addObject:p];

[p release];

}

       
//将找到的key对应分组下的联系人装到字典中

       
[self.dataSource
setValue:mGroup
forKey:key];
   
}
//   
NSLog(@"%@",self.dataSource);  
验证

   

   
//取出所有的key值并排序
//   
NSArray *allkeys = [dict.allKeys
sortedArrayUsingSelector:@selector(compare:)];
   
//使用排好序的key值数组,初始化self.orderedkeys属性
   
self.orderedKeys
=
[NSMutableArray
arrayWithArray:[dict.allKeys
sortedArrayUsingSelector:@selector(compare:)]]; 
 
}

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

   
return
self.orderedKeys.count;

}


-
(NSInteger)tableView:(UITableView
*)tableView
numberOfRowsInSection:(NSInteger)section
{
   
return
[self.dataSource[self.orderedKeys[section]]
count];
}
-
(UITableViewCell
*)tableView:(UITableView
*)tableView
cellForRowAtIndexPath:(NSIndexPath
*)indexPath
{

   
NSString
*key =
self.orderedKeys[indexPath.section];

//根据key值获取字典中的value值

NSMutableArray
*group
= self.dataSource[key];

//根据cell的row下标获取数组中对应的元素

Person
*person =
group[indexPath.row];

//根据数据模型的model对象储存的数据判断,到底要使用哪一种cell

if
([person.gender
isEqualToString:@"男"])
{

       
BoyCell
*cell =
[tableView dequeueReusableCellWithIdentifier:kBoyCell
forIndexPath:indexPath];

cell.person
=
person;

       
return
cell;
   
}else{

GirlCell
*cell =
[tableView dequeueReusableCellWithIdentifier:kGirlCell
forIndexPath:indexPath];

[cell setValueByPerson:person];

return
cell;

   
}
//设置区头

- (NSString
*)tableView:(UITableView
*)tableView
titleForHeaderInSection:(NSInteger)section{

return
self.orderedKeys[section];

}
—————————————————————————————
建立Person的model
Person.h
@interface
Person
: NSObject

@property(nonatomic,copy)NSString
*name;//姓名

@property(nonatomic,copy)NSString
*gender;//姓别

@property(nonatomic,copy)NSString
*age;//年龄

@property(nonatomic,copy)NSString
*phone;//电话号码

@property(nonatomic,copy)NSString
*imageName;//图片
@end
Person.m
-
(void)dealloc{

self.imageName
=
nil;

self.name
=
nil;

self.age
=
nil;

self.phone
=
nil;

self.gender
=
nil;

[super
dealloc];

}


//防止使用字典赋值的时候,没有找到相应的key值Crash

-
(void)setValue:(id)value
forUndefinedKey:(NSString
*)key{
}
@end
————————————————————————————
BoyCell.m
#import
"BoyCell.h"

#import "Person.h"

@interface
BoyCell
()
@property(nonatomic,retain)UIImageView
*photoView;

@property(nonatomic,retain)UILabel
*nameLabel;

@property(nonatomic,retain)UILabel
*genderLabel;

@property(nonatomic,retain)UILabel
*photoLabel;
@end

@implementation
BoyCell

-(void)dealloc{

self.nameLabel
=
nil;

self.photoLabel
=
nil;

self.genderLabel
=
nil;

self.photoView
=
nil;

self.person
=
nil;

[super
dealloc];

}


//重写person的setter方法

- (void)setPerson:(Person
*)person{

if
(_person
!=
person) {

       
[_person
release];

_person
=
[person retain];

}

   
//使用person的属性为cell上的空间赋值

self.photoView.image
=
[UIImage
imageNamed:person.imageName];

self.nameLabel.text
=
person.name;

self.genderLabel.text
=
person.gender;

self.photoLabel.text
=
person.phone;

}


//图片空间
10  10 60 60

- (UIImageView
*)photoView{

if
(_photoView
==
nil)
{

       
self.photoView
=
[[[UIImageView
alloc]initWithFrame:CGRectMake(10,
10,
60,
60)]autorelease];

self.photoView.backgroundColor
=
[UIColor
yellowColor];

}

   
return
[[_photoView
retain]autorelease];

}


//姓名 90 10 60
30

- (UILabel
*)nameLabel{

if
(_nameLabel
==
nil)
{

       
self.nameLabel
=
[[[UILabel
alloc]initWithFrame:CGRectMake(90,
10,
60,
30)]autorelease];

self.nameLabel.backgroundColor
=
[UIColor
redColor];

}

   
return
[[_nameLabel
retain]autorelease];

}


//性别 170 10 60
30

- (UILabel
*)genderLabel{

if
(_genderLabel
==
nil)
{

       
self.genderLabel
=
[[[UILabel
alloc]initWithFrame:CGRectMake(170,
10,
60,
30)]autorelease];

self.genderLabel.backgroundColor
=
[UIColor
yellowColor];

}

   
return
[[_genderLabel
retain]autorelease];

}


//电话 90 50 140
30

- (UILabel
*)photoLabel{

if
(_photoLabel
==
nil)
{

       
self.photoLabel
=
[[[UILabel
alloc]initWithFrame:CGRectMake(90,
45,
140,
30)]autorelease];

self.photoLabel.backgroundColor
=
[UIColor
grayColor];

}

   
return
[[_photoLabel
retain]autorelease];

}


//重写cell的自定义方法

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

if
(self
=
[super
initWithStyle:style
reuseIdentifier:reuseIdentifier])
{

       
[self.contentView
addSubview:self.photoView];

[self.contentView
addSubview:self.nameLabel];

[self.contentView
addSubview:self.genderLabel];

[self.contentView
addSubview:self.photoLabel];

}

   
return
self;

}
————————————————————————————————
GirlCell.h
-
(void)setValueByPerson
: (Person
*)person;
GirlCell.m
#import "GirlCell.h"
#import "Person.h"

@interface
GirlCell
()
@property(nonatomic,retain)UIImageView
*photoView;

@property(nonatomic,retain)UILabel
*nameLabel;

@property(nonatomic,retain)UILabel
*genderLabel;

@property(nonatomic,retain)UILabel
*phoneLabel;
@end
@implementation GirlCell
-
(id)initWithStyle:(UITableViewCellStyle)style
reuseIdentifier:(NSString
*)reuseIdentifier{

if
(self
=
[super
initWithStyle:style
reuseIdentifier:reuseIdentifier])
{

       
[self.contentView
addSubview:self.photoView];

[self.contentView
addSubview:self.nameLabel];

[self.contentView
addSubview:self.genderLabel];

[self.contentView
addSubview:self.phoneLabel];

}

   
return
self;

}



- (void)setValueByPerson
: (Person
*)person;{

self.nameLabel.text
=
person.name;

self.phoneLabel.text
=
person.phone;

self.genderLabel.text
=
person.gender;

self.photoView.image
=
[UIImage
imageNamed:person.imageName];

}




//图片 170 10 60
60

- (UIImageView
*)photoView{

if
(_photoView
==
nil)
{

       
self.photoView
=
[[[UIImageView
alloc]initWithFrame:CGRectMake(170,
10,
60,
60)]autorelease];

self.photoView.backgroundColor
=
[UIColor
greenColor];

self.photoView.layer.cornerRadius
=
30.0;

self.photoView.layer.masksToBounds
=
YES;

}

   
return
[[_photoView
retain]autorelease];

}


//name10 10 60
30

- (UILabel
*)nameLabel{

if
(_nameLabel
==
nil)
{

       
self.nameLabel
=
[[[UILabel
alloc]initWithFrame:CGRectMake(10,
10,
60,
30)]autorelease];

self.nameLabel.backgroundColor
=
[UIColor
yellowColor];

}

   
return
[[_nameLabel
retain]autorelease];

}


//姓别 90 10 60
30

- (UILabel
*)genderLabel{

if
(_genderLabel
==
nil)
{

       
self.genderLabel
=
[[[UILabel
alloc]initWithFrame:CGRectMake(90,
10,
60,
30)]autorelease];

self.genderLabel.backgroundColor
=
[UIColor
greenColor];

}

   
return
[[_genderLabel
retain
]autorelease];

}


//电话10 50 140
30

- (UILabel
*)phoneLabel{

if
(_phoneLabel
==
nil)
{

       
self.phoneLabel
=
[[[UILabel
alloc]initWithFrame:CGRectMake(10,
45,
140,
30)]autorelease];

self.phoneLabel.backgroundColor
=
[UIColor
redColor];

}

   
return
[[_phoneLabel
retain
]autorelease];

}
最终效果:
Cell自适应高度及自定义cell混合使…


=======================================================
欢迎学习本文,未经博主允许,禁止转载!
上一篇:vuex - 学习日记


下一篇:08-UIKit(UITableTableViewCell、自定义Cell、xcode调试)