一、用xcode构建项目,创建一个有tableView的视图,用纯代码的形式实现:
1、创建一个UIViewController类,定义一个UITableView,实现TableView的委托和数据源协议
#import@interface TableViewController : UIViewController { } @property (nonatomic,retain) UITableView *tableView; @end
实现UITableView对象的初始化,声明一个tableData的数组对象用来保存tableView中得数据
#import "TableViewController.h" @interface TableViewController (){ NSMutableArray *tableData; //tableView数据存放数组 } @end @implementation TableViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { tableData = [[NSMutableArray alloc] init]; } return self; } - (void)viewDidLoad { [super viewDidLoad]; [self initTableView]; } //初始化tableView; -(void)initTableView{ CGRect frame = self.view.frame; _tableView = [[UITableView alloc] initWithFrame:CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height)]; //代理类 _tableView.delegate = self; //数据源 _tableView.dataSource = self; [self.view addSubview:_tableView]; }
创建自定义的UITableViewCell类,声明需要用到的控件对象和方法:
#import
@interface TableViewCell : UITableViewCell{
}
//用户名
@property(nonatomic,retain) UILabel *name;
//用户介绍
@property(nonatomic,retain) UILabel *introduction;
//用户头像
@property(nonatomic,retain) UIImageView *userImage;
//给用户介绍赋值并且实现自动换行
-(void)setIntroductionText:(NSString*)text;
//初始化cell类
-(id)initWithReuseIdentifier:(NSString*)reuseIdentifier;
@end
初始化Cell的用户控件,实现方法:
#import "TableViewCell.h" @implementation TableViewCell -(id)initWithReuseIdentifier:(NSString*)reuseIdentifier{ self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier]; if (self) { [self initLayuot]; } return self; } //初始化控件 -(void)initLayuot{ _name = [[UILabel alloc] initWithFrame:CGRectMake(71, 5, 250, 40)]; [self addSubview:_name]; _userImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 66, 66)]; [self addSubview:_userImage]; _introduction = [[UILabel alloc] initWithFrame:CGRectMake(5, 78, 250, 40)]; [self addSubview:_introduction]; } //赋值 and 自动换行,计算出cell的高度 -(void)setIntroductionText:(NSString*)text{ //获得当前cell高度 CGRect frame = [self frame]; //文本赋值 self.introduction.text = text; //设置label的最大行数 self.introduction.numberOfLines = 10; CGSize size = CGSizeMake(300, 1000); CGSize labelSize = [self.introduction.text sizeWithFont:self.introduction.font constrainedToSize:size lineBreakMode:NSLineBreakByClipping]; self.introduction.frame = CGRectMake(self.introduction.frame.origin.x, self.introduction.frame.origin.y, labelSize.width, labelSize.height); //计算出自适应的高度 frame.size.height = labelSize.height+100; self.frame = frame; } - (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; } @end