Autolayout 使用文本调整 UIButton 的大小,然后调整容器视图

Autolayout resize UIButton with text and then the container view

我正在从 xib 文件加载带有按钮的视图。

按钮(绿色)具有本地化的变量文本。我需要 UIButton 随文本动态调整大小,然后容器视图(红色)应调整为按钮大小,这样容器视图就不会有额外的 space。

因为整个容器视图应该在背景清晰的视图中水平居中,并且文本不应该看起来像左对齐或右对齐。我添加了背景颜色以清楚地标记:)

是否可以使用 XCode 自动布局来实现?

注: 我发现如果我使用

view.translatesAutoresizingMaskIntoConstraints = YES;

然后按钮随文本和超级 view/container 视图调整大小。但是后来我无法将框架设置到所需的位置,无论我将其设置为什么,它的原点始终是 (0,0)。也许这是混合布局引擎的限制。

我的最终解决方案变成了,

UIButton *sbt = [UIButton buttonWithType:UIButtonTypeCustom];
[sbt setImage: [UIImage imageNamed:@"cog-wheel"] forState:UIControlStateNormal];
[sbt setTitle:NSLocalizedString(@"Settings", @"") forState:UIControlStateNormal];
[sbt setTitleColor:[UIColor colorWithHexString:@"005173"] forState:UIControlStateNormal];
[sbt setTitleColor:[UIColor colorWithHexString:@"a2b9ce"] forState:UIControlStateHighlighted|UIControlStateSelected];
[sbt addTarget:self action:@selector(didPressSettingsButton) forControlEvents:UIControlEventTouchUpInside];
[sbt sizeToFit];
CGFloat sh = sbt.frame.size.height;
CGFloat yc = self.view.frame.size.height - sh - sh/2;
sbt.center = CGPointMake(self.view.center.x, yc);
[self.view addSubview:sbt];