Calling UIAlertController inside a UITableViewCell

一世执手 提交于 2019-12-02 11:27:22

You can try to use delegate

protocol AlertShower{
    func showAlert(TableCustomCell)
}

class TableCustomCell: UITableViewCell {
    var delegate: AlertShower?

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

in the 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

    }
}

Present is only available to ViewControllers. You are going to have to redirect the touch event to your view controller. The most common way of doing this would be having a delegate property in your UITableViewCell.

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

It's not working for me. Here is my code:

import UIKit
protocol AlertShower{
    func showAlert(_: allListsCell)
}

// prototype table cell...
class allListsCell: UITableViewCell {
    var delegate: AlertShower?
    @IBOutlet var cellSelected:    UILabel!
    var colorIndex = Int()        // point directly back to colors[]

    @IBAction func colorEditButton(_ sender: UIButton, forEvent event: UIEvent) {
        self.delegate?.alertShower(sender:self)  // ERROR...
    }
}

The error above is from the compiler:
"Value of type 'AlertShower' has no member 'alertShower'"

The rest of the code:

class tableViews: UITableViewController, AlertShower {
    func showAlert(_: allListsCell) {
    }

    func showAlert(sender:allListsCell) {

        // show alert here

    }
...
}

...help?

I ran into a similar problem myself when creating a custom activity indicator from a subclassed UIView. What I did was create the 'show' function (in the subclass) and pass in a UIViewController parameter, like so:

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

Simply call it in your view controller like so:

CustomClass.play(inView: self)

Hopefully this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!