[英]UIButton: calculate height of UIButton based on titleLabel Text
我在自定义UITableViewCell中有一个自定义UIButton。 我想基于按钮的titleLabel的可变文本内容,在自定义表格单元格中设置UIButton的高度。
我尝试了以下方法来计算高度
[NSString sizeWithFont:constrainedToSize:lineBreakMode:];
但是我无法按照titleLabel成功更改按钮的高度。
此外,由于此按钮是自定义UITableViewCell的一部分,因此我还需要根据自定义UIButton的高度来更改单元格的高度。
在实现UITableView的委托和数据源方法的ViewController中,我尝试通过以下方法确定高度
- (CGFloat) tableView: (UITableView *) tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath
但没有成功。
什么是解决此问题的最佳解决方案或方法?
假设您的按钮的宽度为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);
看来您做对了,但请记住:
heightForRowAtIndexPath
必须返回CGFloat
sizeWithFont
为您提供文本高度,您需要添加按钮的填充和单元格
使用constrainedToSize:CGSizeMake(###,MAXFLOAT)
,其中###是您的文本宽度
lineBreakMode:UILineBreakModeWordWrap
当然
您也可以使用[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.