【发布时间】:2014-05-22 21:45:06
【问题描述】:
我无法根据自己的限制设置UITableViewCell 的高度。
我在UITableView 的每个单元格中都有一个UILabel,其中高度不固定,取决于此UILabel 的高度。
我在更新标签内容后尝试在单元格上设置框架,但没有任何反应。请在下面找到我的代码:
//On my controller
- (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CommentCell";
CommentCell *commentCell = [tView dequeueReusableCellWithIdentifier:CellIdentifier];
if (commentCell == nil) {
commentCell = [[CommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Comment *comment;
if (commentsArray.count > indexPath.row) {
comment = [commentsArray objectAtIndex:indexPath.row];
}
[commentCell setComment:comment];
[commentCell setCommonFields];
currentCellheight = commentCell.contentLabel.frame.size.height + 40;
DDLogInfo(@"Current Cell Height: %f", currentCellheight);
return commentCell;
}
//On my custom Cell (CommentCell.m)
-(void)setCommonFields {
if (self.comment != nil) {
self.contentLabel.text = self.comment.content;
self.contentLabel.numberOfLines = 0;
CGSize maximumLabelSize = CGSizeMake(self.contentLabel.frame.size.width, FLT_MAX);
CGRect expectedLabelRect = [self.contentLabel.text boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:nil context:nil];
CGRect newFrame = self.contentLabel.frame;
newFrame.size.height = expectedLabelRect.size.height;
self.contentLabel.frame = newFrame;
}
}
由于heightForRowAtIndexPath 方法,我还尝试设置高度,但此方法称为之前 cellForRowAtIndexPath 更新我的标签。
我没有更多的想法来解决这个问题。
提前谢谢你。
【问题讨论】:
-
没有魔法,你需要在
heightForRowAtIndexPath方法中确定你的身高并返回。cellForRowAtIndexPath中不能设置单元格的高度
标签: objective-c dynamic uitableview height