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.
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}
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With