Tunds
Tunds

Reputation: 1817

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

Upvotes: 19

Views: 45846

Answers (7)

JKvr
JKvr

Reputation: 649

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}

Upvotes: 22

sagarmahi onwork
sagarmahi onwork

Reputation: 117

Swift 5

let frameSize: CGPoint = CGPoint(x:self.view.bounds.midX, y:self.view.bounds.midY)

let frameSize: CGPoint = CGPoint(x:yourView.bounds.midX, y:yourView.bounds.midY)

Or

 let frameSize: CGPoint = self.view.center

Upvotes: 1

Regina
Regina

Reputation: 1

How about this?

let width = 80
let height = 80

let

topStoriesActivityIndicator: DTIActivityIndicatorView = DTIActivityIndicatorView(frame: CGRect(x: view.bounds.midX - ( width * 0.5), y: view.bounds.midY - ( height * 0.5) , width: width, height: height))

This may be able to help resolve the problem

Upvotes: 0

Jakub
Jakub

Reputation: 13860

Swift 3:

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

Upvotes: 7

Samir Thebti
Samir Thebti

Reputation: 305

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!

Upvotes: 16

Said Sikira
Said Sikira

Reputation: 4543

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))

Upvotes: 11

Mudith Chathuranga Silva
Mudith Chathuranga Silva

Reputation: 7444

Try this :-

var midY = self.view.frame.height / 2
var midX = self.view.frame.width / 2

Upvotes: 4

Related Questions