I am trying to use a Swift function to place a circle in the centre of a view so it is always on centre regardless of screen size. I can draw the circle at a point defined by a
Your screenCentre()
function won't work in viewDidLoad
because the view
is not yet sized to the screen, therefore its center is not in the middle of the screen.
Use this instead:
func screenCentre() -> CGPoint {
return CGPoint(x: UIScreen.mainScreen().bounds.midX, y: UIScreen.mainScreen().bounds.midY)
}
Note that I am using a CGPoint instead of a tuple, but the effect is the same. Also, the above function doesn't need to be in your view controller or any other class since it doesn't reference self
. It can be a global function.
Since Swift style guidelines encourage making methods over global functions, you might prefer to put the function in an extension like this:
extension UIScreen {
var centre: CGPoint {
return CGPoint(x: bounds.midX, y: bounds.midY)
}
}
Which can be called like this:
let centre = UIScreen.mainScreen().centre
print(centre)