我正在尝试以编程方式将按钮添加到iOS中菜单的水平中心。这样,每个按钮都将显示在上一个按钮的下方。
我的菜单是一个名为的UIView viewToPlaceButtonsOn
,我有一个变量来存储放置的最后一个按钮previousButton
。
似乎很简单,对不对?谁能帮我弄清楚为什么我弄错了吗?
- (void)makeButton:(NSString*) buttonTitle {
UIButton* menuButton = [[UIButton alloc] init];
[menuButton setTitle: buttonTitle forState:UIControlStateNormal];
[menuButton setBackgroundColor:[UIColor redColor]];
[viewToPlaceButtonsOn addSubview:menuButton];
[viewToPlaceButtonsOn addConstraint:[NSLayoutConstraint constraintWithItem:menuButton
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:previousButton
attribute:NSLayoutAttributeCenterX
multiplier:1.0f
constant:0.0f]];
[viewToPlaceButtonsOn addConstraint:[NSLayoutConstraint constraintWithItem:menuButton
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:previousButton
attribute:NSLayoutAttributeTop
multiplier:1.0f
constant:50.0f]];
[viewToPlaceButtonsOn addConstraint:[NSLayoutConstraint constraintWithItem:menuButton
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0F
constant:200]];
[viewToPlaceButtonsOn addConstraint:[NSLayoutConstraint constraintWithItem:menuButton
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0F
constant:40]];
NSLog(@"Button's Frame: %f x %f (%f x %f)", [menuButton frame].origin.x, [menuButton frame].origin.y, [menuButton frame].size.width, [menuButton frame].size.height);
previousButton = menuButton;
}
几件事情立刻浮现出来。你需要设置
menuButton.translatesAutoresizingMaskIntoConstraints = NO;
为了使您的约束正确无误,否则自动布局将添加自己的布局。
另外,由于当时尚未运行布局,因此您的NSLog也将不准确。调用layoutSubviews之后,您的视图框架将通过自动布局设置。要确认这一点,您可以在方法调用结束时使用调试器打印按钮
po menuButton
然后让它继续,然后暂停程序,复制并粘贴上次声明中获取的按钮的内存地址,您应该看到已设置框架
po 0x039484
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句