简体   繁体   中英

Swift - dynamically change size of UIButton

I'm trying to dynamically change frame of UIButton, but it doesn't work.

@IBOutlet weak var button1: UIButton!

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

I'm guessing that I should reload button after frame is changed. Can anybody help?

Auto Layout is preventing you from updating your button's frame. Here are 3 different ways you can make this work from easiest to set up to hardest:

  1. Turn off Auto Layout. In Interface Builder, click on your View Controller. Then in the File Inspector on the far right, uncheck Use Auto Layout .

  2. Define your button programmatically in 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. Set up 4 constraints for your button (horizontal offset from superview leading margin, vertical offset from top layout guide, width, and height). Set up @IBOutlets for these constraints and then update their constant properties in code.

Just use this code will work fine:

button.layer.frame = newFrame

Or you will need to reset the center of the button:

button.frame = newFrame
button.center = newCenter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM