Swift - dynamically resizes UIButton
I am trying to dynamically change the UIButton frame 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 am guessing that I have to reload the button after changing the frame. Can anyone please help?
source to share
Automatic layout prevents you from updating the frame with buttons. Here are three different ways to make this work the easiest to set up:
-
Disable automatic layout. In the Builder interface, click on the View controller. Then in the File Inspector at the far right, uncheck the Use Auto Layout box.
-
Define your program 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)
-
Configure 4 constraints for your button (horizontal offset from top margin of supervisor, vertical offset from top layout guide, width and height). Configure
@IBOutlets
for these constraints and then update their propertiesconstant
in code.
source to share