自动布局使用文本然后调整容器视图的UIButton的大小 [英] Autolayout resize UIButton with text and then the container view

查看:99
本文介绍了自动布局使用文本然后调整容器视图的UIButton的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am loading a view with buttons from a xib file.

按钮(绿色)具有本地化的可变文本.我需要使用文本来动态调整UIButton的大小,然后将容器视图(红色)调整为按钮大小,以便容器视图没有额外的空间.

The button (green) has localized variable text. I need the UIButton to be resized dynamically with the text and then the container view (red) should be resized to the button size, so that container view does not have extra space.

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

Since the whole container view should be horizontally middle in a view with a clear background and the text should not look like aligned in left or right. I have added background color to mark clearly :)

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

Is it possible to do it using XCode auto layout?

注意: 我发现如果我使用

view.translatesAutoresizingMaskIntoConstraints = YES;

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

then the button resizes with text as well as the super view/container view. But then I could not set the frame to the desired place, its origin is always (0,0), whatever I set it to. Maybe that's a restriction for mixing layout engines.

推荐答案

我的最终解决方案变为

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];

这篇关于自动布局使用文本然后调整容器视图的UIButton的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆