如何使用tableViewCell向viewController添加视图?

时间:2017-08-07 20:56:09

标签: swift

我有一个tableViewCell,它为tableview中的每个单元格保存一些函数。我希望其中一个函数向视图显示activityIndicator,以防止用户与应用程序交互,直到该功能完成。通常可以使用以下方法完成:

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

    }

这个问题是self.view.center无法使用,因为此函数位于tableViewCell中,因此self指的是tableViewCell,因此self.view不可用。如何将此活动指示符添加到tableViewCell的tableView中,尽管它位于tableViewCell

1 个答案:

答案 0 :(得分:1)

创建协议,例如:

protocol MyTableViewCellDelegate { 
    func showActivityIndicator()
}

然后在你的UITableViewCell中创建一个对MyTableViewCellDelegate的引用:

var delegate: MyTableViewCellDelegate?

然后让您的控制器符合您的新协议,例如:

class MyViewController: UIViewController, MyTableViewCellDelegate {

...

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

设置你的细胞&#39;委托成为你的控制者。然后,只要您的单元格需要显示ActivityIndi​​cator,您需要调用的是:

delegate?.showActivityIndicator()
相关问题