在UITableView原型单元格中使用UIAlertController报错求助
UITableViewCell中弹UIAlertController报错的解决办法
问题描述
我有一个带原型单元格的UITableView,单元格里有个举报评论的按钮。调用UIAlertController时出现两个错误:
Value of tableViewCell has no member present."nil" requires a contextual type.
下面的代码在其他场景能正常运行,问题出在哪?
func displayAlert() { // Declare Alert message let dialogMessage = UIAlertController(title: "Test", message: "Test", preferredStyle: .alert) // Create OK button with action handler let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in print("Ok button tapped") self.deleteRecord() }) //Add OK and Cancel button to dialog message dialogMessage.addAction(ok) // Present dialog message to user self.present(dialogMessage, animated: true, completion: nil) } func deleteRecord() { print("Delete record function called") }
问题原因与解决办法
第一个错误的根源
present(_:animated:completion:)是UIViewController独有的方法,你现在把displayAlert写在UITableViewCell类里了,Cell本身没有这个方法,所以才会报tableViewCell has no member present的错。
第二个错误的由来
这是附带的小问题,因为第一个核心错误没解决,编译器对completion: nil的类型推断出了问题。只要搞定第一个错误,这个错误会自动消失。
具体解决步骤
- 别在Cell里直接弹Alert:把弹Alert的操作交给Cell所在的ViewController来处理,用闭包实现最方便:
- 给自定义Cell添加闭包属性:
class CustomTableViewCell: UITableViewCell { // 用来传递举报按钮点击事件的闭包 var onReportTapped: (() -> Void)? // 举报按钮的点击事件响应 @IBAction func reportButtonClicked(_ sender: UIButton) { onReportTapped?() } } - 在ViewController的
cellForRowAt方法中绑定闭包:func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "你的Cell标识符", for: indexPath) as! CustomTableViewCell cell.onReportTapped = { [weak self] in // 这里调用ViewController里的弹Alert方法 self?.displayAlert() } return cell }
- 给自定义Cell添加闭包属性:
- 把
displayAlert和deleteRecord移到ViewController中:这样self.present调用的就是ViewController的方法,不会再报错,同时completion: nil的类型也能被正确推断,第二个错误随之消失。
内容的提问来源于stack exchange,提问作者submariner
相关产品推荐
相关产品推荐

