UIButton中心位置不随旋转更新

时间:2014-12-05 18:47:27

标签: ios xcode rotation uibutton

我有一个程序,可以在中心动态生成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;

}

2 个答案:

答案 0 :(得分:0)

代码中按钮的坐标一旦添加到视图中就会被修复。如果要在屏幕旋转时更新按钮的框架,则需要在屏幕旋转时触发按钮的重新定位。

故事板中的AutoLayout使这更容易(如果您只想显示一个按钮,那么您可以将其添加到故事板中,并将其hidden属性从NO更改为YES按下其他按钮 - 如果要添加任意数量的按钮,这将没有用,尽管您可以使用隐藏的占位符视图作为定位参考。

答案 1 :(得分:0)

如果要保持按钮x位置,则需要添加自动布局约束。有几种方法可以通过编程方式执行此操作。您可以直接使用NSLayoutConstraint对象,也可以使用Auto Layout的可视格式语言。有关详细信息,请参阅Apple's documentation.