Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the centre of the view

I'm trying to get the center of my view by using the code below, the class being used is from the DTIActivityIndicatorView which add a custom activity indicator to the view.

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

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

But the code above is giving me the following result where the activity indicator isn't centered in the middle.

screenshot

like image 374
Tunds Avatar asked Nov 16 '15 21:11

Tunds


3 Answers

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}
like image 75
JKvr Avatar answered Nov 05 '22 09:11

JKvr


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!

like image 16
Samir Thebti Avatar answered Nov 05 '22 07:11

Samir Thebti


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))
like image 11
Said Sikira Avatar answered Nov 05 '22 08:11

Said Sikira