在 dialog 裡增加 文字輸入框的範例:
基本款:
//textの表示はalertのみ。ActionSheetだとtextfiledを表示させようとすると //落ちます。 let alert:UIAlertController = UIAlertController(title:"action", message: "alertView", preferredStyle: UIAlertControllerStyle.alert) let cancelAction:UIAlertAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler:{ (action:UIAlertAction!) -> Void in print("Cancel") }) let defaultAction:UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:{ (action:UIAlertAction!) -> Void in print("OK") }) alert.addAction(cancelAction) alert.addAction(defaultAction) //textfiledの追加 alert.addTextFieldWithConfigurationHandler({(text:UITextField!) -> Void in }) //実行した分textfiledを追加される。 alert.addTextFieldWithConfigurationHandler({(text:UITextField!) -> Void in }) present(alert, animated: true, completion: nil)
進階款:
let alert:UIAlertController = UIAlertController(title:"action",
message: "alertView",
preferredStyle: UIAlertControllerStyle.alert)
let cancelAction:UIAlertAction = UIAlertAction(title: "Cancel",
style: UIAlertActionStyle.cancel,
handler:{
(action:UIAlertAction!) -> Void in
print("Cancel")
})
let defaultAction:UIAlertAction = UIAlertAction(title: "OK",
style: UIAlertActionStyle.default,
handler:{
(action:UIAlertAction!) -> Void in
print("OK")
})
alert.addAction(cancelAction)
alert.addAction(defaultAction)
alert.addTextField(configurationHandler: {(text:UITextField!) -> Void in
text.placeholder = "first textField"
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
label.text = "ID"
text.leftView = label
text.leftViewMode = UITextFieldViewMode.always
})
alert.addTextField(configurationHandler: {(text:UITextField!) -> Void in
text.placeholder = "second textField"
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
label.text = "PASS"
text.leftView = label
text.leftViewMode = UITextFieldViewMode.always
})
present(alert, animated: true, completion: nil)

存取輸的Text
You can access the textfield with:
let textField = self.alert.textFields![0]
Then to change the placeholder text:
textField.placeholder = "Foo!"
And the keyboard type:
textField.keyboardType = ...
value 是:
textField.text!
資料來源: