How to get the centre of the view

Swift 3:

let someRect: CGRect(x: 0, y: 0, width: 10, height: 10)
let midX = someRect.midX
let midY = someRect.midY

Swift 3

The following code represent the center of Screen:

let frameSize: CGPoint = CGPoint(x: UIScreen.main.bounds.size.width*0.5,y: UIScreen.main.bounds.size.height*0.5)

Hope this help!


Bounds can be different than how size of the view appears. Try using frame and if it doesn't work try using bounds.

var midX = CGRectGetMidX(self.view.bounds)
var midY = CGRectGetMidY(self.view.bounds)

Also since you are positioning your view in the center and then adding width and height, it appears off as well. You should set the frame like this

let topStoriesActivityIndicator: DTIActivityIndicatorView = DTIActivityIndicatorView(frame: CGRect(x: midX - 80.0, y: midY - 80.0, width:80.0, height:80.0))

Swift 4 extension:

extension CGRect {
    var center: CGPoint { .init(x: midX, y: midY) }
}

let someRect = CGRect(x: 10, y: 10, width: 200, height: 40)

let theCenter = someRect.center // {x 110 y 30}