我想在代碼中生成一個視圖。這是我的看法對象UIScrollView與iOS自動佈局約束:錯誤的子視圖的大小
- 的UIScrollView
- 的UIView的層次結構
- 的UIButton
- 的UIView的層次結構
滾動視圖應該是大小的窗口相同。 按鈕應儘可能大。 我使用的是iOS自動佈局,所以我所有的對象的約束字符串看起來像這樣
H:|[object]|
V:|[object]|
我還設置translatesAutoresizingMaskIntoConstraints
到NO
爲每個對象。
問題是該按鈕僅獲取默認的按鈕大小。它的父視圖對象(UIView)只能獲得其子視圖所需的大小。
紅:UIScrollView中/黃色:UIView的
我如何可以強制這些觀點是一樣大的滾動視圖?
當我使用的,而不是個UIScrollView的一切都很正常一個UIView ...
下面是一些代碼:
- (void) viewDidLoad {
[super viewDidLoad];
// SCROLL VIEW
UIScrollView* scrollView = [UIScrollView new];
scrollView.backgroundColor=[UIColor redColor];
scrollView.translatesAutoresizingMaskIntoConstraints = NO;
//CONTAINER VIEW
UIView *containerView = [UIView new];
containerView.translatesAutoresizingMaskIntoConstraints = NO;
containerView.backgroundColor = [UIColor yellowColor];
[scrollView addSubview:containerView];
// CONSTRAINTS SCROLL VIEW - CONTAINER VIEW
[scrollView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[containerView]|"
options:0 metrics:nil
views:@{@"containerView":containerView}]];
[scrollView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[containerView]|"
options:0 metrics:nil
views:@{@"containerView":containerView}]];
// BUTTON
UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.translatesAutoresizingMaskIntoConstraints = NO;
[button setTitle:@"I'm way to small" forState:UIControlStateNormal];
[containerView addSubview:button];
// CONSTRAINTS CONTAINER VIEW - BUTTON
[containerView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[button]|"
options:0 metrics:nil
views:@{@"button":button}]];
[containerView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[button]|"
options:0 metrics:nil
views:@{@"button":button}]];
self.view = scrollView;
}
UPDATE: 我真的不知道,爲什麼會這樣。如果您在IB中設置視圖,請連接插座並在代碼中實例化視圖,滾動視圖的行爲與普通視圖(垂直彈出)類似。它的contentSize計算不正確。更多here。但如何正確地做到這一點?
這是一個非常複雜的解決方案,只是爲了顯示全屏按鈕。希望我回答了技術問題,但我還不清楚爲什麼你這樣做。 – Rob 2013-05-09 22:34:01
請停止在帖子中寫下你的感謝 - 簽名不屬於此處。謝謝! – Undo 2013-06-02 00:42:27