I'm having trouble programmatically moving a button.
I am using this code in viewDidLoad and I am NOT using auto-layout:
button.frame.origin = CGPoint(x: 0, y: 0)
But the button remains in its original position on the screen at runtime.
The strange thing is, the coordinates are actually being updated, but not being represented on the screen.
If I run the following code:
print(button.frame.origin.x) // prints 45.0
button.frame.origin = CGPoint(x: 0, y: 0)
print(button.frame.origin.x) // prints 0.0
But on screen the button remains at 45.
What am I doing wrong?
Change your button position in viewDidAppear
method and it will change it's position at run time and your code will be:
override func viewDidAppear(animated: Bool) {
button.frame.origin = CGPoint(x: 0, y: 0)
}
From this post: Difference between viewDidLoad and viewDidAppear
viewDidLoad
is called exactly once, when the view controller is first loaded into memory. This is where you want to instantiate any instance variables and build any views that live for the entire lifecycle of this view controller. However, the view is usually not yet visible at this point.
viewDidAppear
is called when the view is actually visible, and can be called multiple times during the lifecycle of a View Controller (for instance, when a Modal View Controller is dismissed and the view becomes visible again). This is where you want to perform any layout actions or do any drawing in the UI - for example, presenting a modal view controller.
Perhaps a long shot (?), but...
Instead of:
button.frame.origin = CGPoint(x: 0, y: 0)
Try:
var frame = button.frame
frame.origin = CGPoint(x: 0, y: 0)
button.frame = frame
EDIT: The reason I suggest this is, I think button.frame
returns a copy of the button's frame rect, so you are not directly changing the origin
sub-property of the original CGRect
instance, and that is why the change is not reflected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With