我有一个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
?
答案 0 :(得分:1)
创建协议,例如:
protocol MyTableViewCellDelegate {
func showActivityIndicator()
}
然后在你的UITableViewCell中创建一个对MyTableViewCellDelegate的引用:
var delegate: MyTableViewCellDelegate?
然后让您的控制器符合您的新协议,例如:
class MyViewController: UIViewController, MyTableViewCellDelegate {
...
func showActivityIndicator() {
// implement your ActivityIndicator logic here
}
}
设置你的细胞&#39;委托成为你的控制者。然后,只要您的单元格需要显示ActivityIndicator,您需要调用的是:
delegate?.showActivityIndicator()