【发布时间】:2011-05-07 07:24:31
【问题描述】:
在界面生成器中,按住 Command + = 将调整按钮的大小以适合其文本。我想知道在将按钮添加到视图之前是否可以通过编程方式执行此操作。
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];
【问题讨论】:
-
注意这个非常古老的问题: 如今(2017 年),只需将约束设置为“大于或等于”即可。 (请注意下面 Tad 的回答。)
-
@Fattie “大于或等于”约束不足以与 AutoLayout 兼容。如今(2017 年以上),应该将按钮包装在可以正确调整大小的东西中(Bartłomiej Semańczyk 回答),或者应该将 UIButton 子类化,如stackoverflow.com/a/50575588/1033581
-
嗨@Cœur - 自动布局有很多微妙之处。您可能正在考虑稍微不同的情况?但是,幸运的是,您完全错了 - 尝试一下!只需将 UIButton 放在视图控制器上。显然设置了水平和垂直中心。然后添加 >= 100 宽度约束。它在最新的 iOS 中完美运行。
-
(对于任何不熟悉自动布局的人在这里搜索......只是待定,您根本不需要添加任何东西,并且 UIButton(还有 UILabel 等)将调整大小随着文本的变化自动调整宽度。只需正确限制 H/V 位置。)
-
@Fattie demonstration。特别是在运行时,它的行为是这样的:github.com/Coeur/autolayoutButton/blob/master/buttonSelfSizing/…