0

I want to place my activity indicator in the centre of my table view controller programmatically but when I run my code it always appears in the top left hand corner.

Here is my swift code;

let activityIndicator: UIActivityIndicatorView = {
    let activityIndicator = UIActivityIndicatorView()
    activityIndicator.style = .large
    activityIndicator.hidesWhenStopped = true
    activityIndicator.color = .white
    activityIndicator.startAnimating()
    return activityIndicator
}()

tableView.addSubview(activityIndicator)
    
NSLayoutConstraint.activate([
    activityIndicator.centerXAnchor.constraint(equalTo: tableView.centerXAnchor),
    activityIndicator.centerYAnchor.constraint(equalTo: tableView.centerYAnchor)
])
    
tableView.layoutSubviews()

activity indicator

4
  • try to execute your code inside viewDidLayoutSubviews Commented Mar 2, 2022 at 20:04
  • @LeoDabus You can't implement any code inside that method. Commented Mar 2, 2022 at 20:07
  • Not sure what you mean. You can always override that method in your view controller, stackoverflow.com/a/35097218/2303865 Commented Mar 2, 2022 at 20:23
  • @LeoDabus ah I see what you mean. I’ll try that. Commented Mar 2, 2022 at 20:31

2 Answers 2

1

You need to set activityIndicator.translatesAutoresizingMaskIntoConstraints = false

  lazy var activityIndicator: UIActivityIndicatorView = {
    let activityIndicator = UIActivityIndicatorView()
    activityIndicator.style = .large
    activityIndicator.translatesAutoresizingMaskIntoConstraints = false
    activityIndicator.hidesWhenStopped = true
    activityIndicator.color = .white
    activityIndicator.startAnimating()
    return activityIndicator
}()
Sign up to request clarification or add additional context in comments.

Comments

0

I needed to include the line;

activityIndicator.translatesAutoresizingMaskIntoConstraints = false

1 Comment

Isn't that what the answer by Dinesh suggested ? If that is what helped you, you should probably accept his answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.