how to use values returned by Swift function

前端 未结 5 411
不思量自难忘°
不思量自难忘° 2021-01-26 01:36

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

5条回答
  •  迷失自我
    2021-01-26 01:58

    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)
    

提交回复
热议问题