Home > database >  How do I center a UIActivityIndicatorView programmatically in Swift?
How do I center a UIActivityIndicatorView programmatically in Swift?

Time:03-04

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

CodePudding user response:

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

CodePudding user response:

I needed to include the line;

activityIndicator.translatesAutoresizingMaskIntoConstraints = false
  • Related