简体   繁体   English

UIButton:根据titleLabel文本计算UIButton的高度

[英]UIButton: calculate height of UIButton based on titleLabel Text

I have a custom UIButton in a custom UITableViewCell. 我在自定义UITableViewCell中有一个自定义UIButton。 I want to set the height of the UIButton in the custom table cell based on the variable textual content of the titleLabel of the button. 我想基于按钮的titleLabel的可变文本内容,在自定义表格单元格中设置UIButton的高度。

I tried the following method to calculate the height 我尝试了以下方法来计算高度

[NSString sizeWithFont:constrainedToSize:lineBreakMode:];

but I could not successfully change the button height as per the titleLabel. 但是我无法按照titleLabel成功更改按钮的高度。

Further, as this button is part of a custom UITableViewCell, I also need to change the height of the cell as per the height of the custom UIButton. 此外,由于此按钮是自定义UITableViewCell的一部分,因此我还需要根据自定义UIButton的高度来更改单元格的高度。

In the ViewController implementing the delegate and the datasource methods of the UITableView, I tried to determine the height in the following method 在实现UITableView的委托和数据源方法的ViewController中,我尝试通过以下方法确定高度

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

but was not successful. 但没有成功。

What could be the best solution or approach to solve this? 什么是解决此问题的最佳解决方案或方法?

Assume the width of your button is 145.0f: 假设您的按钮的宽度为145.0f:

CGSize constraintSize;

constraintSize.width = 145.0f;

constraintSize.height = MAXFLOAT;

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

Then you can set the frame: 然后可以设置框架:

frame = CGRectMake(0, 0, 145, size.height);

It seems like you do it right, but remember: 看来您做对了,但请记住:

heightForRowAtIndexPath must return CGFloat sizeWithFont gives you height of text, you need to add padding of your button, and cell heightForRowAtIndexPath必须返回CGFloat sizeWithFont为您提供文本高度,您需要添加按钮的填充和单元格

use constrainedToSize:CGSizeMake(###,MAXFLOAT) where ### is your text width 使用constrainedToSize:CGSizeMake(###,MAXFLOAT) ,其中###是您的文本宽度

lineBreakMode:UILineBreakModeWordWrap of course lineBreakMode:UILineBreakModeWordWrap当然

You can also use [buttonInstance sizeToFit] . 您也可以使用[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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM