Runeaway3
Runeaway3

Reputation: 1447

How to use tableViewCell to add view to viewController?

I have a tableViewCell that holds some functions for each cell in a tableview. I want one of these functions to present an activityIndicator to the view to prevent user interaction with the app until the function is done. Normally this can be done by using:

var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
func exampleFunc(){
        activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0,y: 0,width: 50,height: 50))
        activityIndicator.center = self.view.center //can't be used as self.view doesn't exist because self is a tableviewCell
        activityIndicator.hidesWhenStopped = true
        activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
        view.addSubview(activityIndicator) //also can't be used
        activityIndicator.startAnimating()
        UIApplication.shared.beginIgnoringInteractionEvents()
        if x<y{
            self.activityIndicator.stopAnimating() 
            UIApplication.shared.endIgnoringInteractionEvents()
        }

    }

The problem with this is that the self.view.center cannot be used as this function is housed in the tableViewCell and therefore self is referring to the tableViewCell and so a self.view is not usable. How can I add this activity indicator to the tableView housing the tableViewCell despite it being in the tableViewCell?

Upvotes: 0

Views: 61

Answers (1)

jnelson
jnelson

Reputation: 1225

Create a protocol, such as:

protocol MyTableViewCellDelegate { 
    func showActivityIndicator()
}

Then in your UITableViewCell create a reference to a MyTableViewCellDelegate:

var delegate: MyTableViewCellDelegate?

Then make your controller conform to your new protocol, ex:

class MyViewController: UIViewController, MyTableViewCellDelegate {

...

    func showActivityIndicator() {
        // implement your ActivityIndicator logic here
    }
}

Set your cells' delegate to be your controller. Then whenever your cell needs to show an ActivityIndicator all you need to call is:

delegate?.showActivityIndicator()

Upvotes: 1

Related Questions