我在 uiAlertController 中有一个文本字段,我想检索其中的内容来构建一个对象。我写了以下代码:
let alertController = UIAlertController(title: "Ajouter une description", message: "De quoi sagit il ?", preferredStyle: UIAlertControllerStyle.alert)
alertController.addTextField { (textField : UITextField) -> Void in
textField.placeholder = "Description"
self.theDescription = textField.text!
}
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
self.createArtWithDescription(description: self.theDescription)
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
//
}
为了构建我的对象,我有另一个函数“createArtWithDescription”,但在内部我无法检索 uiAlertController 文本字段的内容。
提前致谢
最佳答案
简短回答:
let okAction = UIAlertAction(title: "OK", style: .default) { (result : UIAlertAction) -> () in
self.theDescription = alertController.textFields?.first?.text
self.createArtWithDescription(description: self.theDescription)
}
长答案:
创建简单的 Playground 用于测试并在执行期间检查所有内容:
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
private var theDescription:String?
private var label:UILabel = UILabel()
override func loadView() {
let view = UIView()
view.backgroundColor = .white
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.text = "Hello World!"
label.textColor = .black
label.backgroundColor = .red
view.addSubview(label)
self.view = view
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let alertController = UIAlertController(title: "Ajouter une description", message: "De quoi sagit il ?", preferredStyle:.alert)
alertController.addTextField { (textField : UITextField) -> () in
textField.placeholder = "Description"
// you cant obtain value here - this block only for config purpose
self.theDescription = textField.text
}
let okAction = UIAlertAction(title: "OK", style: .default) { (result : UIAlertAction) -> () in
// instead use this approach
self.theDescription = alertController.textFields?.first?.text
self.createArtWithDescription(description: self.theDescription)
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
//
}
func createArtWithDescription(description:String?) {
DispatchQueue.main.async {
self.label.text = description
}
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
关于swift - 从 uiAlertController 中的文本字段检索内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47110552/