0

我试图让我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;
}
4

1 回答 1

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 更改此设置。

于 2013-09-16T08:01:08.883 回答