我有一个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
中?
创建一个协议,例如:
protocol MyTableViewCellDelegate {
func showActivityIndicator()
}
然后在 UITableViewCell 中创建对 MyTableViewCellDelegate 的引用:
var delegate: MyTableViewCellDelegate?
然后使您的控制器符合您的新协议,例如:
class MyViewController: UIViewController, MyTableViewCellDelegate {
...
func showActivityIndicator() {
// implement your ActivityIndicator logic here
}
}
将单元格的委托设置为控制器。然后,每当您的单元格需要显示活动指示器时,您只需要调用:
delegate?.showActivityIndicator()