ios 如何在 Swift 中将 TextField 添加到 UIAlertController

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31922349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:12:37  来源:igfitidea点击:

How to add TextField to UIAlertController in Swift

iosswiftuitextfielduialertcontroller

提问by Quintin Balsdon

I am trying to show a UIAlertControllerwith a UITextView. When I add the line:

我试图UIAlertController用一个UITextView. 当我添加该行时:

    //Add text field
    alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
    }        

I get a Runtimeerror:

我收到一个Runtime错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

致命错误:在展开可选值时意外发现 nil

    let alertController: UIAlertController = UIAlertController(title: "Find image", message: "Search for image", preferredStyle: .Alert)

    //cancel button
    let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
        //cancel code
    }
    alertController.addAction(cancelAction)

    //Create an optional action
    let nextAction: UIAlertAction = UIAlertAction(title: "Search", style: .Default) { action -> Void in
        let text = (alertController.textFields?.first as! UITextField).text
        println("You entered \(text)")
    }
    alertController.addAction(nextAction)

    //Add text field
    alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
        textField.textColor = UIColor.greenColor()
    }
    //Present the AlertController
    presentViewController(alertController, animated: true, completion: nil)

This is presented inside my ViewControllervia an IBAction.

这是ViewController通过一个IBAction.

I have downloaded the code from hereand it works fine. I copied and pasted that method into my code and it breaks. The presence of selfon the last line has no impact.

我已经从这里下载了代码,它工作正常。我将该方法复制并粘贴到我的代码中,但它中断了。最后一行self的存在没有影响。

采纳答案by Quintin Balsdon

So I started checking to see what could possibly have been different in my code to the working code. I noticed that my ViewController extends

所以我开始检查我的代码与工作代码中可能有什么不同。我注意到我的 ViewController 扩展了

UITextFieldDelegate

Which apparently means that I need to set the delegate of any child UITextView:

这显然意味着我需要设置任何子 UITextView 的委托:

alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
    searchTextField = textField
    searchTextField?.delegate = self //REQUIRED
    searchTextField?.placeholder = "Enter your search terms"
}

回答by Himanshu Mahajan

Swift 5.1

斯威夫特 5.1

alert.addTextField { (textField) in
    textField.placeholder = "Enter First Name"
}


Use this code, I am running this code in my app successfully.

使用此代码,我在我的应用程序中成功运行此代码。

@IBAction func addButtonClicked(sender : AnyObject){
    let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: UIAlertControllerStyle.Alert)
    alertController.addTextFieldWithConfigurationHandler { (textField : UITextField!) -> Void in
        textField.placeholder = "Enter Second Name"
    }
    let saveAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.Default, handler: { alert -> Void in
        let firstTextField = alertController.textFields![0] as UITextField
        let secondTextField = alertController.textFields![1] as UITextField
    })
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: {
        (action : UIAlertAction!) -> Void in })
    alertController.addTextFieldWithConfigurationHandler { (textField : UITextField!) -> Void in
        textField.placeholder = "Enter First Name"
    }

    alertController.addAction(saveAction)
    alertController.addAction(cancelAction)

    self.presentViewController(alertController, animated: true, completion: nil)
}

Edited: Swift 3.0 version

编辑:Swift 3.0 版本

@IBAction func addButtonClicked(_ sender: UIButton){
    let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: .alert)
    alertController.addTextField { (textField : UITextField!) -> Void in
        textField.placeholder = "Enter Second Name"
    }
    let saveAction = UIAlertAction(title: "Save", style: .default, handler: { alert -> Void in
        let firstTextField = alertController.textFields![0] as UITextField
        let secondTextField = alertController.textFields![1] as UITextField
        print("firstName \(firstTextField.text), secondName \(secondTextField.text)")
    })
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (action : UIAlertAction!) -> Void in })
    alertController.addTextField { (textField : UITextField!) -> Void in
        textField.placeholder = "Enter First Name"
    }

    alertController.addAction(saveAction)
    alertController.addAction(cancelAction)

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

回答by Meagan S.

To add a text field in Swift 3.0:

要在 Swift 3.0 中添加文本字段:

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)

回答by üma?g ?ürm?n

Solution:

解决方案:

Swift 4.2

斯威夫特 4.2

Try the following lines and see if it works:

尝试以下几行,看看它是否有效:

let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: .alert)

alertController.addTextField { (textField : UITextField!) -> Void in
    textField.placeholder = "Enter Second Name"
}

let saveAction = UIAlertAction(title: "Save", style: .default, handler: { alert -> Void in
    let firstTextField = alertController.textFields![0] as UITextField
    let secondTextField = alertController.textFields![1] as UITextField
})

let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil )

alertController.addTextField { (textField : UITextField!) -> Void in
    textField.placeholder = "Enter First Name"
}

alertController.addAction(saveAction)
alertController.addAction(cancelAction)

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

Hope it helps.

希望能帮助到你。

回答by Maihan Nijat

How to add textField to AlertView? Let's keep it short and simple.

如何将 textField 添加到 AlertView?让我们保持简短。

This works for Swift 3.0 and above.

这适用于 Swift 3.0 及更高版本。

var nameField: UITextField?
let alertController = UIAlertController(title: "Add Number", message: nil, preferredStyle: .alert)
// Add textfield to alert view
alertController.addTextField { (textField) in
    nameField = textField
}

First, you instantiate an object of UIAlertControllerand then you add a text field to it by accessing addTextFieldmember of UIAlertControllerclass.

首先,您实例化一个对象,UIAlertController然后通过访问类的addTextField成员向其添加文本字段UIAlertController

回答by Hardik Thakkar

To add alertController with one textField (Swift 5)

使用一个 textField 添加 alertController (Swift 5)

func openAlert(){
    let alertController = UIAlertController(title: "Title", message: "", preferredStyle: .alert)
    alertController.addTextField { (textField : UITextField!) -> Void in
        textField.placeholder = "Enter name"
    }

    let saveAction = UIAlertAction(title: kAlertConfirm, style: .default, handler: { alert -> Void in
        if let textField = alertController.textFields?[0] {
            if textField.text!.count > 0 {
                print("Text :: \(textField.text ?? "")")
            }
        }
    })

    let cancelAction = UIAlertAction(title: kAlertCancel, style: .default, handler: {
        (action : UIAlertAction!) -> Void in })

    alertController.addAction(cancelAction)
    alertController.addAction(saveAction)

    alertController.preferredAction = saveAction

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

回答by iOS

In Swift 4.2 and Xcode 10.1

在 Swift 4.2 和 Xcode 10.1 中

Alert with two Textfieldsand Read TextField text dataand present alert on top of all views.

警报,2个文本框阅读文本字段文本数据对所有视图顶部存在提醒

func alertWithTF(title: String, message: String) {
    //Step : 1
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)

    //Step : 2
    alert.addAction (UIAlertAction(title: "Save", style: .default) { (alertAction) in
        let textField = alert.textFields![0]
        let textField2 = alert.textFields![1]
        if textField.text != "" {
            //Read textfield data
            print(textField.text!)
            print("TF 1 : \(textField.text!)")
        } else {
            print("TF 1 is Empty...")
        }
        if textField2.text != "" {
            //Read textfield data
            print(textField2.text!)
            print("TF 2 : \(textField2.text!)")
        } else {
            print("TF 2 is Empty...")
        }
    })

    //Step : 3
    //For first TF
    alert.addTextField { (textField) in
        textField.placeholder = "Enter your first name"
        textField.textColor = .red
    }
    //For second TF
    alert.addTextField { (textField) in
        textField.placeholder = "Enter your last name"
        textField.textColor = .blue
    }

    //Cancel action
    alert.addAction(UIAlertAction(title: "Cancel", style: .default) { (alertAction) in })
   self.present(alert, animated:true, completion: nil)

}

If you want to present aleert on top of all views.

如果您想在所有视图之上显示警报。

Here from above code remove this last line self.present(alert, animated:true, completion: nil)and add below code.

从上面的代码中删除最后一行self.present(alert, animated:true, completion: nil)并添加下面的代码。

//Present alert on top of all views.
let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = UIWindowLevelAlert + 1

alertWindow.makeKeyAndVisible()

alertWindow.rootViewController?.present(alert, animated:true, completion: nil)

Now call like this

现在这样调用

alertWithTF(title: "This is title", message: "This is message")

回答by 5uper_0leh

For Swift 4.0, You can use this sample of code succesfully tested in my project:

对于 Swift 4.0,您可以使用在我的项目中成功测试的代码示例:

@IBAction func withdrawTapped(_ sender: UIButton) {

  let alertController = UIAlertController(title: "Token withdraw", message: "", preferredStyle: .alert)

  let withdrawAction = UIAlertAction(title: "Withdraw", style: .default) { (aciton) in

    let text = alertController.textFields!.first!.text!

    if !text.isEmpty {
      self.presentAlert(
        title: "Succesful", 
        message: "You made request for withdraw \(textField.text) tokens")
    }
  }

  let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
  }

  alertController.addTextField { (textField) in
    textField.placeholder = "999"
    textField.keyboardType = .decimalPad
  }

  alertController.addAction(withdrawAction)
  alertController.addAction(cancelAction)

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

回答by ram

add TextField to UIAlertController and TextField text Display on UILabel in Swift

在 Swift 中将 TextField 添加到 UIAlertController 和 TextField 文本显示在 UILabel 上

let alert = UIAlertController(title: "Alert", message: "", preferredStyle: .alert)

alert.addTextField { (textField) in
textField.placeholder = "First Name"
}
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
let textField = alert?.textFields![0]
self.label.text = textField?.text  }))

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

回答by Jeremy Andrews

Great answer a slight modification to show how the textfield can be used:

很好的答案,稍作修改以显示如何使用文本字段:

func addRow (row: Int, bodin: String, flag: Int) {
    let alertController = UIAlertController(title: bodin, message: "", preferredStyle: .alert)
    alertController.addAction(UIAlertAction(title: "Save", style: .default, handler: {
        alert -> Void in
        _ = alertController.textFields![0] as UITextField

    }))
    alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

    alertController.addTextField(configurationHandler: {(textField : UITextField!) -> Void in
        switch flag {
        case 0:
            textField.keyboardType = UIKeyboardType.phonePad
            textField.placeholder = "Enter Number"
        case 1:
            textField.keyboardType = UIKeyboardType.emailAddress
            textField.placeholder = "Enter Email"
        default:
            break
        }

    })