swift - 从 UITableViewCell 呈现 UIAlertController

标签 swift xcode

我没有成功从 UITableViewCell 执行 UIAlertController

我已经尝试以编程方式创建一个segue,然后执行它(代码编号1),但它在appDelegate处崩溃(崩溃发生在appDelegate处) 我尝试使用代码 2,但它什么也没做(打印出:“其 View 不在窗口层次结构中!”也许它已连接?), 我尝试调用 viewController.Swift 中的函数来呈现和/或继续,但它也没有成功

仅当按下单元格中的特定按钮时才会出现警报

代码1:

UIApplication.shared.keyWindow?.rootViewController?.present(refreshAlert, animated: true, completion: nil)

代码2:

var segue = UIStoryboardSegue.init(identifier: "goAlart", source: ViewController(), destination: refreshAlert)

segue.perform()

我在 appDelegate 得到的异常是:线程 1:信号 SIGABRT 当我删除“segue.perform()”时,我没有收到任何错误

最佳答案

正如评论中提到的,显示警报的好地方是 didSelectRow at。 我看不到其余的代码,但我假设您已经初始化了 UIAlertController 并且属性 refreshAlert 指向它。如果 refreshAlert 存储在 ViewController 中,那么这应该可以工作:

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        present(refreshAlert, animated: true, completion: nil)
  }

编辑: 由于您需要在单元格中按下按钮时显示警报,因此最好的方法是委托(delegate)协议(protocol):

protocol MyCusomCellDelegate: NSObjectProtocol {
  func didPressAlertButton()
}

在您的单元格中,您声明委托(delegate)属性:

  weak var delegate: MyCusomCellDelegate?

按下按钮后,您将调用委托(delegate)方法:

delegate?.didPressAlertButton()

在 ViewController 中,您遵守协议(protocol):

extension ViewController: MyCusomCellDelegate {
  func didPressAlertButton() {
    present(refreshAlert, animated: true, completion: nil)
  }
}

最后,在cellForRowAt indexPath

cell.delegate = self

如果您需要为不同的单元格显示不同的警报,那么您应该在委托(delegate)调用中传递一些数据。

关于swift - 从 UITableViewCell 呈现 UIAlertController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57554823/

相关文章:

swift - 如何从 Xcode 的单元测试中排除 NSManagedObject 自动生成的 Coredata 实体类?

iOS 推送通知 : how to detect if the user tapped on notification when the app is in background?

ios - 如何将数据从 View Controller 传递到导航 Controller ,然后再传递到另一个 View Controller ?

xcode - Swift:通过比较类型来过滤协议(protocol)数组

ios - Storyboard中的标签没有采用正确的本地化值

iphone - Objective-C:与 CoreData 的多对多关系

ios - 适应不断变化的模型 Swift iOS?

objective-c - iPhone-配置单元格中文本的位置

xcode - 如何使用 SwiftUI 从 TabView 内的 ForEach 中删除项目?

swift - 弹出窗口中没有摘要信息 -- Option-Click