//UITableViewCell系统本身的行高自适应属性,结合UILabel的行数属性就形成了简单的高度自适应。
#import "ViewController.h"
#define WIDTH [[UIScreen mainScreen] bounds].size.width
#define HEIGHT [[UIScreen mainScreen] bounds].size.height
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *dataSource;
@end
@implementation TableViewController
- (void)viewDidLoad {
[superviewDidLoad];
self.dataSource = [NSMutableArray array];
[self createTableViewLayout];
[self loadCustomDataSource];
}
- (void)createTableViewLayout{
self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,64,WIDTH,HEIGHT -64)];
self.tableView.delegate =self;
self.tableView.dataSource =self;
[self.tableView registerClass:[UITableViewCell class]forCellReuseIdentifier:@"Cell"];
//K1:预估行高,实现后方可自适应行高
self.tableView.estimatedRowHeight = 60;
[self.view addSubview:self.tableView];
}
- (void)loadCustomDataSource{
//创建随机数据源
for (NSInteger i =0; i <100; i++) {
NSUInteger random =arc4random() %3 +1;
if (random ==1) {
[self.dataSource addObject:[NSString stringWithFormat:@"发个v就扑个皮革u工作据哦撒大哥如果配股俄国举手%ld",i]];
}else if (random ==2){
[self.dataSource addObject:[NSStringstringWithFormat:@"不是孤独是个屁哦糖果色皮革苏东坡故意恶下好我和发生屁啊物业费阿赛分为分也无法释放是废说法啊沙发沙发沙发上物废物废物%ld",i]];
}else{
[self.dataSource addObject:[NSStringstringWithFormat:@"法赛分啊少女啊的阿萨感动而我却一哦南隆达省不会看到个啊茶发烧发烧发烧发撒发啥发啥发撒发啥发撒分身乏术发撒发撒发撒发撒发撒为分完皮肤与王菲好我和发生屁啊物业费阿赛分为分也无法释放是废说法啊沙发沙发沙发上物废物废物%ld",i]];
}
}
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell * ccell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
//K2:自适应高度就是利用UILabel的numberOfLines = 0属性
ccell.textLabel.numberOfLines =0;
ccell.textLabel.text = self.dataSource[indexPath.row];
return ccell;
}