Reputation: 11961
I am trying to center my UIActivityIndicatorView in a UITableView, this is how I am creating my UIActivityIndicatorView:
indicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) as UIActivityIndicatorView
//Set the activity indictor center
indicator.center = self.view.center
//Hide the indicator when its stopped.
indicator.hidesWhenStopped = true
//Set the style of the activity indicator
indicator.style = UIActivityIndicatorView.Style.white
//Set the background colour of the activity indicator
indicator.backgroundColor = UIColor(white: 0.0, alpha: 0.6)
//Make the activity indicator have rounded corners
indicator.layer.cornerRadius = 15
//Add activity indicator to view
self.view.addSubview(indicator)
//Start activity indicator
self.indicator.startAnimating()
But when I scroll up on my UITableView I can't see my UIActivityIndicatorView, I have tried the following:
override func viewWillLayoutSubviews() {
self.indicator.center = self.view.center
}
But that did not work.
I have also tried:
override func viewWillLayoutSubviews() {
self.indicator.translatesAutoresizingMaskIntoConstraints = true
self.indicator.frame = self.view.bounds
self.indicator.center = self.view.center
}
Also did not work, what am I doing wrong?
This is happening when I scroll down, then select an item in my table view then the activity indicator will appear.
Upvotes: 0
Views: 1000
Reputation: 51
I had a situation where everything is fine on the UIViewController, but there were problems with the UIActivityIndicatorView on the UITableViewController.
Please pay attention to the proposed solution. In my case, activityView is stretched to the whole form and this solution helped me out. https://stackoverflow.com/a/41886375/7938405
Upvotes: 0
Reputation: 464
You can't center inside the UITableViewController, as it is a scroll view, and the scroll view is the View Controller's view. However, you can center it inside the window's view like so:
// get the visible window
let window = UIApplication.shared.keyWindow!
let viewActivity = UIActivityIndicatorView(style: .whiteLarge)
// set your activity indicator's center to the center of the screen
viewActivity.center = window.center
viewActivity.hidesWhenStopped = true
// add the indicator to the active window (not your uitableviewcontroller)
// and make sure it is at the front (so it is visible)
window.addSubview(viewActivity)
window.bringSubviewToFront(viewActivity)
viewActivity.startAnimating()
You could also accomplish this by grabbing your root Navigation, or tab view controller, and centering it inside there, as well.
Upvotes: 0