Pheel Pheel - 3 days ago 7
Swift Question

Get center of any UIView in Swift

I'm trying to write a global function that adds an activityIndicator to any view (mostly imageViews though) by calling such function.

The function I have right now is made of:

public func addActivityIndicatorToView(activityIndicator: UIActivityIndicatorView, view: UIView){

//activityIndicator configuration ...
activityIndicator.center = view.center
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
}


But I don't get the center of the view for some reason.

I've also tried various solutions around SO and Google, but none worked until now.

Is there any way to get the center point and set the activityIndicator to any UIView?

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


}

Hope that could help.

Comments