【问题标题】:Adding TextField to AlertController breaks AlertController将 TextField 添加到 AlertController 会中断 AlertController
【发布时间】:2017-11-26 18:07:43
【问题描述】:

我目前正在尝试打开一个带有 TextField 的 AlertController。运行时

let configAlert = UIAlertController(title: "Configure Add-On", message: "Enter Your Add-On Name:", preferredStyle: UIAlertControllerStyle.alert)

configAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction!) in
      // Handle Input          
}))

present(configAlert, animated: true, completion: nil)

一切正常,但只要我添加了 TextField

configAlert.addTextField { (textField) in
    textField.placeholder = "Name"
}

警报需要大约 10 倍的时间才能打开,然后立即关闭,我在控制台中收到此错误大约 30 次垃圾邮件:

2017-11-26 13:04:08.985783-0500 MinelyMod[380:14792] Warning: Attempt to dismiss from view controller <UISplitViewController: 0x147e0a6a0> while a presentation or dismiss is in progress!

这是失败的完整 AlertController

let configAlert = UIAlertController(title: "Configure Add-On", message: "Enter Your Add-On Name:", preferredStyle: UIAlertControllerStyle.alert)

configAlert.addTextField { (textField) in
    textField.placeholder = "Name"
}

configAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction!) in
    // Handle Input            
}))

present(configAlert, animated: true, completion: nil)

【问题讨论】:

  • 什么样的事件会触发你的代码被调用?看起来它发生在其他控制器的演示动画中间。
  • 确保从主线程调用present(_: UIViewController) 方法。顺便说一句,您还应该发布您的句柄输入代码。
  • 我已将它复制并粘贴到一个新项目中,它对我来说效果很好。我正在使用 xcode 8.3。试试看它是否在那里工作,如果是,问题出在其他地方。
  • @LeoDabus 不处理输入就崩溃了。

标签: iphone swift alert textfield uialertcontroller


【解决方案1】:
let alertController = UIAlertController(title: "Title", message: "", preferredStyle: .alert)

    alertController.addAction(UIAlertAction(title: "Save", style: .default, handler: {
        alert -> Void in
        let textField = alertController.textFields![0] as UITextField
        // do something with textField
    }))
    alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

    alertController.addTextField(configurationHandler: {(textField : UITextField!) -> Void in
        textField.placeholder = "Search"
    })

    self.present(alertController, animated: true, completion: nil)

【讨论】:

  • 不推荐纯代码答案。请解释 OP 做错了什么...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-17
  • 2023-04-02
  • 2018-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多