Get the center of any UIView in Swift

I am trying to write a global function that adds an ActivityIndicator to any view (mainly ImageViews) by calling such a function.

Now I have a function:

public func addActivityIndicatorToView(activityIndicator: UIActivityIndicatorView, view: UIView){ //activityIndicator configuration ... activityIndicator.center = view.center view.addSubview(activityIndicator) activityIndicator.startAnimating() } 

But for some reason I do not get the center of the eye.

I also tried various solutions around SO and Google, but so far no one has worked.

Is there a way to get the center point and set the ActivityIndicator for any UIView?

+7
center swift uiview
source share
3 answers

I easily reproduced your problem (see my comment). I think this may be an auto layout problem. Maybe you can use constraints rather than 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() } 

Hope this helps.

+11
source share

Swift 3:

 activityIndicator.center = CGPoint(x: view.height/2, y: view.width/2) 

or you can try:

 activityIndicator.center = view.center 
+7
source share

The center property refers to the viewview. Therefore, if your view is {10, 10, 20, 20} , center will be {20, 20} .

I assume you want to center activityIndicator in view .

You can do

 activityIndicator.center = CGPointMake(view.width/2, view.height/2) 
+5
source share

All Articles