数据解析模型设置的技巧

最直接的计算cell高度的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/#pragma mark - 代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取出帖子模型
    HYWTopic *topic = self.topics[indexPath.row];

    // 文字的最大尺寸
    CGSize maxSize = CGSizeMake([UIScreen mainScreen].bounds.size.width - 4 * HYWTopicCellMargin, MAXFLOAT);
//    CGFloat textH = [topic.text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:maxSize].height;
    CGFloat textH = [topic.text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size.height;

    // cell的高度
    CGFloat cellH = HYWTopicCellTextY + textH + HYWTopicCellBottomBarH + 2 * HYWTopicCellMargin;

    return cellH;
}

set方法和get方法都重写的话,成员变量也不会自动生成

1
2
3
4
5
6
7
8
9
10
11
12
13
- (CGFloat)cellHeight
{
    if (!_cellHeight) {
        // 文字的最大尺寸
        CGSize maxSize = CGSizeMake([UIScreen mainScreen].bounds.size.width - 4 * HYWTopicCellMargin, MAXFLOAT);
        // 计算文字的高度
        CGFloat textH = [self.text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size.height;

        // cell的高度
        _cellHeight = HYWTopicCellTextY + textH + HYWTopicCellBottomBarH + 2 * HYWTopicCellMargin;
    }
    return _cellHeight;
}

MJExtension模型属性名和键值名替换可以统一处理,如果有规律的话