Autolayout resize UIButton with text and then the

2019-07-23 08:27发布

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

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 :)

Is it possible to do it using XCode auto layout?

enter image description here

Note: I found that if I use

view.translatesAutoresizingMaskIntoConstraints = YES;

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.

1条回答
干净又极端
2楼-- · 2019-07-23 08:41

My final solutions becomes,

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

enter image description here

查看更多
登录 后发表回答