簡體   English   中英

Swift - 動態改變UIButton的大小

[英]Swift - dynamically change size of UIButton

我正在嘗試動態更改UIButton的框架,但它不起作用。

@IBOutlet weak var button1: UIButton!

@IBAction func btn_move2_touchupinside(sender: AnyObject, forEvent event: UIEvent) {
           button1.frame = CGRectMake(0, 0, 100, 100)
}

我猜我應該在幀改變后重新加載按鈕。 有人可以幫忙嗎?

自動布局阻止您更新按鈕的框架。 以下3種不同的方法可以使這項工作從最簡單到最難設置:

  1. 關閉自動布局。 在Interface Builder中,單擊View Controller。 然后在最右側的文件檢查器中 ,取消選中“ 使用自動布局”

  2. ViewDidLoad編程方式定義按鈕:

     let button = UIButton.buttonWithType(.System) as UIButton button.frame = CGRectMake(200, 200, 100, 100) button.addTarget(self, action: "btn_move2_touchupinside:forEvent:", forControlEvents: .TouchUpInside) button.setTitle("New Button", forState: .Normal) self.view.addSubview(button) 
  3. 為您的按鈕設置4個約束(從超視圖前緣開始的水平偏移,從頂部布局向導的垂直偏移,寬度和高度)。 為這些約束設置@IBOutlets ,然后在代碼中更新它們的constant屬性。

只需使用此代碼即可正常工作:

button.layer.frame = newFrame

或者您需要重置按鈕的中心:

button.frame = newFrame
button.center = newCenter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM