Autolayout使用文本和容器视图调整UIButton的大小
问题描述:
我使用xib文件中的按钮加载视图。Autolayout使用文本和容器视图调整UIButton的大小
按钮(绿色)具有局部变量文本。我需要使用文本动态调整UIButton的大小,然后容器视图(红色)应该调整为按钮大小,以便容器视图不会有额外的空间。
由于整个容器视图应该在背景清晰的视图中水平居中,并且文本不应该看起来像左对齐或右对齐。我已经添加了背景颜色来清楚标记:)
是否可以使用XCode自动布局进行操作?
注: 我发现,如果我用
view.translatesAutoresizingMaskIntoConstraints = YES;
然后按钮与文字以及超级视图/容器视图调整大小。但后来我无法将框架设置到所需的位置,它的原点总是(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];
你可以在你的情况下使用堆栈查看和设置按钮宽度> = 0。 –