iOS:UIButton根据文本长度调整大小

2024-04-14

In interface builder, holding Command + = will resize a button to fit its text. I was wondering if this was possible to do programmatically before the button was added to the view.

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12]];
[button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
// I need to know the width needed to accomodate NSStringVariable
[button setTitle:NSStringVariable forState:UIControlStateNormal]; 
// So that I can set the width property of the button before addSubview
[button setFrame:CGRectMake(10, 0, width, fixedHeight)];
[subNavigation addSubview:button];

在 UIKit 中,NSString 类添加了一些内容,可以从给定的 NSString 对象获取以某种字体呈现时所占用的大小。

文件是here https://web.archive.org/web/20140828211856/http://developer.apple.com/library/ios/documentation/uikit/reference/NSString_UIKit_Additions/Reference/Reference.html。现在是here https://developer.apple.com/documentation/foundation/nsstring?language=objc#topics已弃用。

简而言之,如果你去:

CGSize stringsize = [myString sizeWithFont:[UIFont systemFontOfSize:14]]; 
//or whatever font you're using
[button setFrame:CGRectMake(10,0,stringsize.width, stringsize.height)];

...您将按钮的框架设置为您正在渲染的字符串的高度和宽度。

您可能想要在该 CGSize 周围尝试一些缓冲区空间,但您将从正确的位置开始。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

iOS:UIButton根据文本长度调整大小 的相关文章

随机推荐