iOS动态单元格高度基于动态文本视图基于文本

时间:2013-07-23 20:34:19

标签: ios uitableview uitextview tableview frame

我正在尝试让我的UITableViewCell根据textview正确调整大小,textView根据文本动态调整大小。但是,我不能让他们一起工作。以下是我到目前为止的情况?现在单元格高度正确,但contentSize.height未根据- (void)viewDidLoad { [super viewDidLoad]; // Set the label properties! self.titleLabel.text = self.releaseTitle; self.pubDateLabel.text = self.pubDate; self.attachmentsLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)self.attatchments.count]; self.contentTextView.text = self.summary; } - (void)viewWillAppear:(BOOL)animated { } - (void)viewDidAppear:(BOOL)animated { [self.tableView reloadData]; // Set the proper height of the content cell of the text CGRect frame = self.contentTextView.frame; frame.size.height = self.contentTextView.contentSize.height; self.contentTextView.frame = frame; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return self.contentTextView.contentSize.height; } 调整大小。

{{1}}

1 个答案:

答案 0 :(得分:1)

您需要在heightForRowAtIndexPath,中计算单元格的高度,例如

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *theText=[[_loadedNames objectAtIndex: indexPath.row] name];
CGSize labelSize = [theText sizeWithFont:[UIFont fontWithName: @"FontA" size: 15.0f] constrainedToSize:kLabelFrameMaxSize];
return kHeightWithoutLabel+labelSize.height;

}

您可以通过设置kLabelFrameMaxSize

为标签尺寸设置一些限制
#define kLabelFrameMaxSize CGSizeMake(265.0, 200.0)

然后通过添加具有可变标签高度的恒定高度来返回高度。

另外,为了保持一致,您应该使用相同的方法在cellForRowAtIndexPath中设置框架,而不是使用sizeToFitMultipleLines

- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
FQCustomCell *_customCell = [tableView dequeueReusableCellWithIdentifier: @"CustomCell"];
if (_customCell == nil) {
    _customCell = [[FQCustomCell alloc] initWithStyle: UITableViewCellStyleValue1 reuseIdentifier: @"CustomCell"];
}


_customCell.myLabel.text = [[_loadedNames objectAtIndex: indexPath.row] name];
_customCell.myLabel.font = [UIFont fontWithName: @"FontA" size: 15.0f];

UIView *backView = [[UIView alloc] initWithFrame: CGRectZero];
backView.backgroundColor = [UIColor clearColor];
_customCell.backgroundView = backView;

CGSize labelSize = [_customCell.myLabel.text sizeWithFont:_customCell.myLabel.font constrainedToSize:kLabelFrameMaxSize];
_customCell.myLabel.frame = CGRectMake(5, 5, labelSize.width, labelSize.height);

return _customCell;
}

您可以为UILabel,UIButton,Cell更改此项。

相关问题