在 UITableViewCell 中调用 UIAlertController

Calling UIAlertController inside a UITableViewCell

我试图在我的函数被调用时从我的 UITtableViewCell 中调用一个 UIAlertController。它给我一个错误,说 present is not available。我知道它不在 ViewController 之内。我正在寻找一种访问它的方法。

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code

    let tapGestureShareImageView = UITapGestureRecognizer(target: self, action: #selector(self.shareImageTouchUpInside))
    shareImageView.addGestureRecognizer(tapGestureShareImageView)
    shareImageView.isUserInteractionEnabled = true
}

@objc func shareImageTouchUpInside() {
    showAction()
}

func showAction() {
    let alertController = UIAlertController(title: "Action Sheet", message: "What do you like to do", preferredStyle: .alert)

    let okButton = UIAlertAction(title: "Done", style: .default, handler: { (action) -> Void in
        print("Ok button tapped")
    })

    let deleteButton = UIAlertAction(title: "Skip", style: .destructive, handler: { (action) -> Void in
        print("Delete button tapped")
    })

    alertController.addAction(okButton)
    alertController.addAction(deleteButton)

    present(alertController, animated: true, completion: nil)
}

Present 仅适用于 ViewController。您将不得不将触摸事件重定向到您的视图控制器。最常见的做法是在 UITableViewCell 中有一个委托 属性。

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-ID276

你可以尝试使用delegate

protocol AlertShower{
    func showAlert(TableCustomCell)
}

class TableCustomCell: UITableViewCell {
    var delegate: AlertShower?

    @IBAction func showClicked(_ sender: UIButton) {
        self.delegate?.alertShower(sender:self)
    }
}

在VC

class viewController: UIViewController, AlertShower {

    override func viewDidLoad() {
        super.viewDidLoad()

    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

         let cell = areaSettTable.dequeueReusableCell(withIdentifier:CellIdentifier1) as! TableCustomCell

         cell.delegate = self

         return cell
    }

    func showAlert(sender:TableCustomCell) {

      // show alert here

    }
}

我 运行 在从子类 UIView 创建自定义 activity 指标时遇到了类似的问题。我所做的是创建 'show' 函数(在子类中)并传入 UIViewController 参数,如下所示:

public func play(inView view: UIViewController) {
//Perform action here
view.present(alertController, animated: true, completion: nil)
}

只需在您的视图控制器中调用它,就像这样:

CustomClass.play(inView: self)

希望这对您有所帮助!