我有一个程序,可以在中心动态生成UIButtons 按下另一个按钮的屏幕。 旋转设备时,按钮不会更新x坐标。
以下是我创建按钮的代码:
- (IBAction)createButton:(UIButton *)sender {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundColor:[UIColor redColor]];
[button addTarget:self action:@selector(doSomething:) forControlEvents:UIControlEventTouchUpInside];
button.frame = CGRectMake(self.xCoord,self.yOffset,100.0,120.0);
[self.view addSubview:button];
_yOffset = _yOffset+130;
}
XCoord和self.yOffset在viewDidLoad中设置:
- (void)viewDidLoad {
[super viewDidLoad];
self.yOffset = 109;
self.xCoord = self.view.bounds.size.width/2-50;
}
答案 0 :(得分:0)
代码中按钮的坐标一旦添加到视图中就会被修复。如果要在屏幕旋转时更新按钮的框架,则需要在屏幕旋转时触发按钮的重新定位。
故事板中的AutoLayout使这更容易(如果您只想显示一个按钮,那么您可以将其添加到故事板中,并将其hidden
属性从NO
更改为YES
按下其他按钮 - 如果要添加任意数量的按钮,这将没有用,尽管您可以使用隐藏的占位符视图作为定位参考。
答案 1 :(得分:0)
如果要保持按钮x位置,则需要添加自动布局约束。有几种方法可以通过编程方式执行此操作。您可以直接使用NSLayoutConstraint对象,也可以使用Auto Layout的可视格式语言。有关详细信息,请参阅Apple's documentation.