我在UITableViewCell中有一个UILabel,我想根据上下文将它作为多行,我使用砌体来管理autolayout,这里是代码 CommunityTableViewCell.m:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
_postContentLabel = [UILabel new];
_postContentLabel.numberOfLines = 2;
_postContentLabel.font = DefaultFont(15);
_postContentLabel.textColor = COLOR(117, 117, 117);
[self.contentView addSubview:_postContentLabel];
[self makeConstraints];
}
return self;
}
- (void)makeConstraints{
[_postContentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(_userAvatar);
make.right.equalTo(_groupNameButton);
make.top.equalTo(_postTitleLabel.mas_bottom).offset(20);
make.height.greaterThanOrEqualTo(@20);
}];
}
- (void)updateCellWithModel:(PostsModel *)model{
if (model.content && ![model.content isEqualToString:@""]) {
_postContentLabel.text = model.content;
_postContentLabel.preferredMaxLayoutWidth = _postContentLabel.frame.size.width;
[_postContentLabel sizeToFit];
} else{
_postContentLabel = nil;
[_postContentLabel removeFromSuperview];
}
[self updateConstraints];
}
- (void)updateConstraints {
//some other code here
[super updateConstraints];
}
CommunityViewController.m:
- (void)viewDidLoad {
[super viewDidLoad];
_communityTableView = [UITableView new];
_communityTableView.delegate = self;
_communityTableView.dataSource = self;
_communityTableView.estimatedRowHeight = 80;
_communityTableView.rowHeight = UITableViewAutomaticDimension;
[_communityTableView registerClass:[CommunityTableViewCell class] forCellReuseIdentifier:@"CommunityTableViewCell"];
[self.view addSubview:_communityTableView];
[self makeConstraints];
[self requestPostData];
}
- (void)makeConstraints{
[_communityTableView mas_makeConstraints:^(MASConstraintMaker *make) {
UIEdgeInsets padding = UIEdgeInsetsMake(0, 0, 0, 0);
make.edges.equalTo(self.view).insets(padding);
}];
}
- (void)requestPostData{
[[NetEngine engine] GET:[NSString stringWithFormat:@"posts"] success:^(id responseObject) {
//receive the data
[self.communityTableView reloadData];
} failure:^(NSError *error) {
}];
}
#pragma mark - TableView DataSource & Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return _postArrary.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
CommunityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommunityTableViewCell" forIndexPath:indexPath];
PostsModel *model = _postArrary[indexPath.row];
//some other code
[cell updateCellWithModel:model];
return cell;
}
在这里输入代码
它不会显示最多2行,它只显示一行,但当我向下滚动或向后滚动或拉动以刷新tableview时,它显示2行。
我不知道发生了什么。