您好,我正在以编程方式创建按钮。我正在 ios6 和 ios7 4 英寸屏幕和 3.5 英寸屏幕上运行一些应用程序。我需要在同一位置显示所有版本的按钮。
所以我想为此使用自动布局概念。我知道如何以编程方式创建按钮,但我不知道如何为按钮应用自动布局概念。这是我的代码:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(aMethod:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];
最佳答案
试试这个,
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(aMethod:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);
[self.view addConstraints:@[
//view1 constraints
[NSLayoutConstraint constraintWithItem:button
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:padding.top],
[NSLayoutConstraint constraintWithItem:button
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:padding.left],
[NSLayoutConstraint constraintWithItem:button
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:-padding.bottom],
[NSLayoutConstraint constraintWithItem:button
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeRight
multiplier:1
constant:-padding.right],
]];
[self.view addSubview:button];
更新:
button.autoresizingMask = (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin);
引用链接:Autoresizing masks programmatically vs Interface Builder / xib / nib
关于ios - 使用 NSAutolayout 概念如何在 ios 中的同一位置显示所有版本的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23131886/