1.自定义cell
自定义cell就是创建一个UITableViewCell的子类。
把cell上的控件创建都封装在子类中,简化UIViewController中的代码
子视图控件添加到cell的contentView上。
//注册自定义的单元格
[self.tableView registerClass:[CustomTableViewCell class] forCellReuseIdentifier:@"CELL"];
// 绘制单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//从重用队列中取单元格 需要注意的是,重用标示符必须和上面注册的一致
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
//得呈现内容
//呈现内容分两步 1.将内容取出;2.内容显示出来
//1.取出内容 分析数据结构。取出内容分两步:a.数组中的字典取出来;b.把字典中所要用的内容取出
NSDictionary *dic = [self.dataArray objectAtIndex:indexPath.row];//a
NSString *contentString = [dic objectForKey:@"content"];//b
NSString* nameString = [dic objectForKey:@"user_name"];//b
//2.呈现内容 内容的大载体是刚才自定义的cell,实际是显示在cell上的label上的
cell.contentLabel.text = contentString;
cell.nameLabel.text = nameString;
cell.headIconImageView.image = [UIImage imageNamed:@"crazyLOL.jpg"];
NSNumber *create_at = [dic objectForKey:@"created_at"];
NSDate *myDate = [NSDate dateWithTimeIntervalSince1970:[create_at doubleValue]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd日hh:mm:ss"];
NSString* resultTimeStr = [formatter stringFromDate:myDate];
cell.createTimeLabel.text = resultTimeStr;
// cell.imageView.image
return cell;
}
2.自适应高度为NSString对象的一个方法
//返回cell高度的代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//NSString有一个方法,可以根据内容来返回一个矩形大小
//代理方法执行是有顺序的,这里是先执行返回高度的代理方法,再执行创建单元格的代理方法
//取得内容
NSDictionary *dic = [self.dataArray objectAtIndex:indexPath.row];
NSString *contentStr = [dic objectForKey:@content];
//内容自适应高度的方法
//参数解释:
//size:是规定文本显示的最大范围
//options: 按照何种设置来计算计算范围
//attributes:文本内容的一些属性,例如字体大小、字体类型等
//context:上下文,可以规定一些其它设置,但是一般都是nil
//枚举值中的单或意思是要满足所有的枚举值设置
CGRect rect = [contentStr boundingRectWithSize:CGSizeMake(tableView.bounds.size.width, MAXFLOAT) options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
return rect.size.height+50+20;
}