Reputation: 6810
ok, I have added a button to the .swift storyboard, I have then added the following code to my ViewController.swift
@IBOutlet weak var HelloButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
HelloButton.frame.origin.x = view.frame.size.width / 2
}
However when I test it on my iPhone 5s it moves it to the right of my screen and does not make it centered. I am unsure what I need to do to make the button centered.
Yes this is my first helloWorld app, and maybe over my head, but I understand web programing, and I understand to make it center automaticilly I need to have the screen view width total and the button width. I then need to say to the button to divide the screen view width by 2.
for example in CSS we do this
#button{margin:0 auto;}
but this is not HTML or CSS. IT'S SWIFT3
Upvotes: 0
Views: 2508
Reputation: 9136
You should be using Autolayout for accomplishing what you want and the way you do is like the following in your ViewController inside of Main.storyboard: (control + left mouse click -> dragging the blue line upwards and then releasing the control and left mouse click, you will see the popup)
In the popup select the options:
But if you want to do it programmatically, do it in viewWillLayoutSubviews method:
class ViewController: UIViewController {
@IBOutlet weak var button: UIButton!
override func viewWillLayoutSubviews() {
super. viewWillLayoutSubviews()
button.center = view.center
}
}
Upvotes: 2
Reputation: 7736
Add the code to viewDidAppear
that way the actual view has shown up. Also, you should use button.center.x
instead of button.frame.origin.x
if you want to center it
Upvotes: 0
Reputation: 878
In your project Autolayout is enabled? if Auto Layout enabled then Change UI in viewdidLoad: may not give appropriate result. use -viewWillLayoutSubviews method to do UI task, it you want to center your button
myButton.center = self.view.center
Hope it will work.
Upvotes: 0
Reputation: 9923
Try this:
HelloButton.center.x = view.frame.width/2
Yours is not correct because the origin.x
is the first point (top left) of the button view, not the center of the view, you can change it's background color to different color to see it
Also, the variable name should be lowerCase, followed by code convention
Upvotes: 2