1

我在自定义 UITableViewCell 中有一个自定义 UIButton。我想根据按钮 titleLabel 的可变文本内容在自定义表格单元格中设置 UIButton 的高度。

我尝试了以下方法来计算高度

[NSString sizeWithFont:constrainedToSize:lineBreakMode:];

但我无法根据 titleLabel 成功更改按钮高度。

此外,由于此按钮是自定义 UITableViewCell 的一部分,因此我还需要根据自定义 UIButton 的高度更改单元格的高度。

在实现 UITableView 的委托和数据源方法的 ViewController 中,我尝试在以下方法中确定高度

- (CGFloat) tableView: (UITableView *) tableView 
heightForRowAtIndexPath:(NSIndexPath *)indexPath

但没有成功。

解决此问题的最佳解决方案或方法可能是什么?

4

3 回答 3

4

假设您的按钮宽度为 145.0f:

CGSize constraintSize;

constraintSize.width = 145.0f;

constraintSize.height = MAXFLOAT;

CGSize size = [Label.text sizeWithFont:Label.font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; 

然后你可以设置框架:

frame = CGRectMake(0, 0, 145, size.height);
于 2012-09-21T18:56:46.207 回答
2

看起来你做对了,但请记住:

heightForRowAtIndexPathmust returnCGFloat sizeWithFont给你文本的高度,你需要添加按钮的填充,和单元格

使用constrainedToSize:CGSizeMake(###,MAXFLOAT)### 是您的文本宽度

lineBreakMode:UILineBreakModeWordWrap当然

于 2012-09-21T18:40:49.940 回答
1

您也可以使用[buttonInstance sizeToFit].

 UIButton *lineButton = [[UIButton alloc] initWithFrame:CGRectZero];
 // If padding equals "yes, please"
 [lineButton setContentEdgeInsets:UIEdgeInsetsMake(0.0f, 5.0f, 0.0f, 3.0f)];
 [lineButton setTitle:@"Title" forState:UIControlStateNormal];
 [lineButton sizeToFit];
于 2012-12-20T16:23:11.447 回答