问题
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?
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:
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];
来源:https://stackoverflow.com/questions/45548372/autolayout-resize-uibutton-with-text-and-then-the-container-view