Get center of any UIView in Swift
The center
property is relative to a view's superview. So if your view's frame is {10, 10, 20, 20}
, center
is going to be {20, 20}
.
I'm guessing you want to center the activityIndicator
in view
.
You can do
activityIndicator.center = CGPointMake(view.width/2, view.height/2)
Original Answer:
I had reproduce your problem easily (see my comment). I think it could be a problem of auto layout. So may be you can use constraints instead calculate position ?
func addActivityIndicatorToView(activityIndicator: UIActivityIndicatorView, view: UIView){
self.view.addSubview(activityIndicator)
//Don't forget this line
activityIndicator.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
activityIndicator.startAnimating()
}
Updated Code for Swift 5.0:
- From edit by Rob
NSLayoutAttribute.CenterX
is nowNSLayoutConstraint.Attribute.centerX
NSLayoutRelation.Equal
is nowNSLayoutConstraint.Relation.equal
NSLayoutAttribute.CenterY
is nowNSLayoutConstraint.Attribute.centerY
func addActivityIndicatorToView(activityIndicator: UIActivityIndicatorView, view: UIView){
self.view.addSubview(activityIndicator)
//Don't forget this line
activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
view.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0))
activityIndicator.startAnimating()
}
Swift 3:
activityIndicator.center = CGPoint(x: view.width/2, y: view.height/2)
or you can try:
activityIndicator.center = view.center