2017-08-07 44 views
1

我使用xib文件中的按鈕加載視圖。Autolayout使用文本和容器視圖調整UIButton的大小

按鈕(綠色)具有局部變量文本。我需要使用文本動態調整UIButton的大小,然後容器視圖(紅色)應該調整爲按鈕大小,以便容器視圖不會有額外的空間。

由於整個容器視圖應該在背景清晰的視圖中水平居中,並且文本不應該看起來像左對齊或右對齊。我已經添加了背景顏色來清楚標記:)

是否可以使用XCode自動佈局進行操作?

enter image description here

注: 我發現,如果我用

view.translatesAutoresizingMaskIntoConstraints = YES; 

然後按鈕與文字以及超級視圖/容器視圖調整大小。但後來我無法將框架設置到所需的位置,它的原點總是(0,0),無論我設置爲何。也許這是混合佈局引擎的限制。

+0

你可以在你的情況下使用堆棧查看和設置按鈕寬度> = 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]; 

enter image description here

相關問題