https://github.com/potato512/SYDemo_Masonry
在UITableView列表的使用中,因为在自定义的UITableViewCell中页面相对复杂,所以会出现每一个cell都有不同的高度。这时候就需要根据实际内容进行cell的更新约束,其实说到底也就是哪些UI子视图应该显示,或隐藏,哪些UILabel标签高度是这个数值,哪些UILabel标签的高度是那个数值。
这样想的话,我们在研发时就可以根据实际的数据Model进行控制UI的显示,或隐藏,也就是更新UI的约束,以便设置UI的自适应显示;其次再计算出实际的高度用于在UITableView的代理回调方法中设置cell的高度。
先看下效果图
示例代码(model类、cell类)
1、自定义数据model
#import <Foundation/Foundation.h>
@interface TableViewModel : NSObject
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *content;
@property (nonatomic, strong) NSString *imageName;
@property (nonatomic, assign) CGFloat height;
@end
#import "TableViewModel.h"
#import "TableViewCell.h"
@implementation TableViewModel
- (CGFloat)height
{
if (!_height)
{
// 调用cell的方法计算出高度
_height = [TableViewCell heightTableCellWithModel:self];
}
return _height;
}
@end
2、自定义UITableViewCell
#import <UIKit/UIKit.h>
#import "TableViewModel.h"
static NSString *const identifierTableViewCell = @"TableViewCell";
static CGFloat const heightTableViewCell = (10.0 + 30.0 + 10.0 + 30.0 + 10.0 + 80.0 + 10.0);
@interface TableViewCell : UITableViewCell
@property (nonatomic, strong) TableViewModel *model;
+ (CGFloat)heightTableCellWithModel:(TableViewModel *)model;
@end
#import "TableViewCell.h"
static CGFloat const originXY = 10.0;
static CGFloat const heightTitle = 30.0;
static CGFloat const sizeImage = 80.0;
@interface TableViewCell ()
@property (nonatomic, assign) BOOL didSetupConstraints;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *detailLabel;
@property (nonatomic, strong) UIImageView *iconI