我在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文本字段的内容。 谢谢提前
答案 0 :(得分:0)
简短回答:
let okAction = UIAlertAction(title: "OK", style: .default) { (result : UIAlertAction) -> () in
self.theDescription = alertController.textFields?.first?.text
self.createArtWithDescription(description: self.theDescription)
}
答案很长:
创建简单的游乐场,以便在执行期间测试和检查所有内容:
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()
的更多信息