gpt4 book ai didi

swift - 如何使用 tableViewCell 将 View 添加到 viewController?

转载 作者:行者123 更新时间:2023-11-28 15:23:54 25 4
gpt4 key购买 nike

我有一个 tableViewCell,它为 tableview 中的每个单元格保存一些函数。我希望其中一个函数向 View 显示 activityIndi​​cator 以防止用户与应用程序交互,直到该函数完成。通常这可以通过使用来完成:

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 中?

最佳答案

创建协议(protocol),例如:

protocol MyTableViewCellDelegate { 
func showActivityIndicator()
}

然后在您的 UITableViewCell 中创建对 MyTableViewCellDelegate 的引用:

var delegate: MyTableViewCellDelegate?

然后让你的 Controller 符合你的新协议(protocol),例如:

class MyViewController: UIViewController, MyTableViewCellDelegate {

...

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

将您的单元格的委托(delegate)设置为您的 Controller 。然后,每当您的单元格需要显示 ActivityIndi​​cator 时,您需要调用的是:

delegate?.showActivityIndicator()

关于swift - 如何使用 tableViewCell 将 View 添加到 viewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45555579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com