【问题标题】:UIAlertController in UITableView is returning nilUITableView 中的 UIAlertController 返回 nil
【发布时间】:2017-01-19 19:09:10
【问题描述】:

我在 UITableView 中使用 UIAlertController。它在 tableview.delegate = self 附近返回 nil 值。这里的 alertC 是呈现警报的函数。当按下按钮时,我正在从 tableViewCell 调用 alertC 函数。

class AdminPlaces: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!
private var placeNames = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
    self.getDataFromFirebase {
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.reloadData()
    }

   func alertC() {
    let ac = UIAlertController(title: "Delete", message: "Are you sure to delete the place", preferredStyle: .alert)
    let yesAction = UIAlertAction(title: "Yes", style: .default, handler: nil)

    let noAction = UIAlertAction(title: "No", style: .cancel, handler: nil)
    ac.addAction(yesAction)
    ac.addAction(noAction)
    self.present(ac, animated: true, completion: nil)
}

}


class AdminPlacesCell: UITableViewCell {

@IBOutlet weak var placeName: UILabel!

@IBOutlet weak var delete: UIButton!
@IBOutlet weak var edit: UIButton!

override func awakeFromNib() {
    edit.alpha = 0
    delete.alpha = 0
}
func configure(place: String) {
    placeName.text = place
}

func showButtons() {
    UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
        self.edit.alpha = 1
        self.delete.alpha = 1
    }, completion: nil)

}



@IBAction func onEditClicked(_ sender: Any) {
}
@IBAction func onDeleteClicked(_ sender: Any) {
    let adminPlaces = AdminPlaces()
    adminPlaces.alertC()
}
}

我不明白是什么问题。为什么它在 tableView.delegate=self 附近返回 nil?正确的做法是什么??

提前致谢

【问题讨论】:

  • 请检查此链接,因为它解决了我的问题。 link

标签: ios swift uitableview uialertcontroller tableviewcell


【解决方案1】:

这里有几个问题。 1.alertC存在于ViewDidLoad中。将此功能移出此处。 2.如下代码:

let adminPlaces = AdminPlaces()
adminPlaces.alertC()

说创建一个全新的 AdminPlaces 实例并在新实例上调用 alertC()。这与持有 tableView 的 AdminPlaces 不同。新的尚未呈现,因此不会显示警报。 3. 您的警报存在于 ViewController 上,而您的单元格没有直接访问它的方法。

使用 UITableViewDelegate 方法 tableView:commit:editingStyle。当用户从编辑模式中删除单元格时,将调用此方法。从这里调用你的 alertC() 方法。

【讨论】:

  • 感谢您的回复。但只是没有在viewDidLoad中写alertC()函数。这只是我的复制粘贴中的一个错误。无论如何谢谢你。
  • 我从这个链接得到了答案。有同样问题的朋友可以参考一下。 link
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
  • 2014-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-21
相关资源
最近更新 更多