![](/img/trans.png)
[英]Redrawing UIButton using CGRectMake doesn't update UIButton position?
[英]UIButton center position doesn't update with rotation
我有一個程序,可以通過按下另一個按鈕在屏幕中央動態生成UIButton。 旋轉設備時,按鈕未更新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;
}
將代碼中的按鈕坐標添加到視圖后,該坐標將被固定。 如果要在屏幕旋轉時更新按鈕的框架,則需要在屏幕旋轉時觸發按鈕的重新放置。
情節提要中的“自動布局”使此操作更加容易(如果您只希望顯示一個按鈕,則可以將其添加到情節提要中,並在按下另一個按鈕時將其hidden
屬性從“ NO
YES
更改為YES
是”-如果您願意,這將無濟於事添加任意數量的按鈕,盡管您可以使用隱藏的占位符視圖作為定位參考)
如果要保持按鈕的x位置,則需要添加“自動布局”約束。 有兩種方法可以通過編程方式執行此操作。 您可以直接使用NSLayoutConstraint對象,也可以使用自動布局的可視格式語言。 有關更多信息,請參閱Apple文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.