【问题标题】:How to add TextField to UIAlertController in Swift如何在 Swift 中将 TextField 添加到 UIAlertController
【发布时间】:2015-11-02 12:46:28
【问题描述】:

我正在尝试用UITextView 显示UIAlertController。当我添加该行时:

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

我收到Runtime 错误:

致命错误:在展开可选值时意外发现 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)

这是通过IBAction 在我的ViewController 中呈现的。

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

【问题讨论】:

  • UITextField,而不是UITextView ?

标签: ios swift xcode uitextfield uialertcontroller


【解决方案1】:

斯威夫特 5.1

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

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

@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)
}

编辑: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)
}

【讨论】:

    【解决方案2】:

    在 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)
    

    【讨论】:

      【解决方案3】:

      解决方案:

      斯威夫特 4.2

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

      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)
      

      希望对你有帮助。

      【讨论】:

      • 这两个alertController.addTextField的顺序对吗?似乎“第二名”会出现在“名”上方。
      【解决方案4】:

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

      UITextFieldDelegate
      

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

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

      【讨论】:

        【解决方案5】:

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

        这适用于 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
        }
        

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

        【讨论】:

          【解决方案6】:

          使用一个 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)
          }
          

          【讨论】:

            【解决方案7】:

            对于 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)
            }
            

            【讨论】:

              【解决方案8】:

              在 Swift 4.2 和 Xcode 10.1 中

              带有两个文本字段读取文本字段文本数据的警报并在所有视图上显示警报

              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)
              
              }
              

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

              这里从上面的代码中删除最后一行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)
              

              现在这样调用

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

              【讨论】:

                【解决方案9】:

                UIAlertControllerUITextfield 在最新 Apple Swift 版本 5.1.3

                UIViewController 中创建UIAlertControllerlazy 变量,添加UITextFieldDelegate,在UIButton 操作上显示警报

                class  YourViewController: UIViewController,UITextFieldDelegate {
                
                    //Create Alert Controller Object here
                    lazy var alertEmailAddEditView:UIAlertController = {
                
                        let alert = UIAlertController(title:"My App", message: "Customize Add/Edit Email Pop Up", preferredStyle:UIAlertController.Style.alert)
                
                        //ADD TEXT FIELD (YOU CAN ADD MULTIPLE TEXTFILED AS WELL)
                        alert.addTextField { (textField : UITextField!) in
                            textField.placeholder = "Enter  emails"
                            textField.delegate = self
                        }
                
                        //SAVE BUTTON
                        let save = UIAlertAction(title: "Save", style: UIAlertAction.Style.default, handler: { saveAction -> Void in
                            let textField = alert.textFields![0] as UITextField
                            print("value entered by user in our textfield is: \(textField.text)")
                        })
                        //CANCEL BUTTON
                        let cancel = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: {
                            (action : UIAlertAction!) -> Void in })
                
                
                        alert.addAction(save)
                        alert.addAction(cancel)
                
                        return alert
                    }()
                
                
                    //MARK:- UIButton Action for showing Alert Controller
                    @objc func buttonClicked(btn:UIButton){
                        self.present(alertEmailAddEditView, animated: true, completion: nil)
                    }
                
                    //MARK:- UITextFieldDelegate
                    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
                        textField.resignFirstResponder()
                        return true
                    }
                }
                

                编码愉快!! :)

                【讨论】:

                  【解决方案10】:

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

                  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
                          }
                  
                      })
                  

                  【讨论】:

                    【解决方案11】:

                    将 TextField 添加到 UIAlertController 和 TextField 文本在 Swift 中的 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)
                    

                    【讨论】:

                      【解决方案12】:

                      Swift5

                      第一个类符合 UITextFieldDelegate ,然后创建新的 textField 属性

                          private var myTextField : UITextField?
                      
                          // now where u want to add code
                          let alertContoller = UIAlertController.init(title: "Add", message: "My message to user", preferredStyle: .alert)
                          alertContoller.addTextField { (textField) in
                              // make sure your outside any property should be accessed with self here
                              self.myTextField = textField
                              //Important step assign textfield delegate to self
                              self.myTextField?.delegate = self 
                              self.myTextField?.placeholder = self.textFieldPlaceholderText
                          }
                          let action = UIAlertAction.init(title: "Ok", style: .default) { action in
                              print("Alert tapped")
                          }
                          alertContoller.addAction(action)
                          present(alertContoller, animated: true, completion:nil)
                      

                      谢谢

                      【讨论】:

                      • 这就是我要找的。我想限制警报控制器内文本字段中的字符。我喜欢你在控制器外部声明textField 的想法。这样我就可以使用textFieldshouldChangeCharactersInRange。真是个好主意。谢谢!
                      【解决方案13】:
                      private func showLoginAlert() {
                          let loginAlert = UIAlertController(title: "Login Using Credentials", message: nil, preferredStyle: .alert)
                          loginAlert.view.tintColor = .systemBlue
                      
                          loginAlert.addTextField { usernameField in
                              usernameField.font = .systemFont(ofSize: 17.0)
                              usernameField.placeholder = "Username"
                          }
                          loginAlert.addTextField { passwordField in
                              passwordField.font = .systemFont(ofSize: 17.0)
                              passwordField.isSecureTextEntry = true
                              passwordField.placeholder = "Password"
                          }
                      
                          let cancelAction = UIAlertAction(title: "Cancel",
                                                           style: .destructive,
                                                           handler: { _ in
                                                              // self.handleUsernamePasswordCanceled(loginAlert: loginAlert)
                          })
                          loginAlert.addAction(cancelAction)
                      
                          let loginAction = UIAlertAction(title: "Login",
                                                          style: .default,
                                                          handler: { _ in
                                                              // self.handleUsernamePasswordEntered(loginAlert: loginAlert)
                          })
                          loginAlert.addAction(loginAction)
                          loginAlert.preferredAction = loginAction
                          present(loginAlert, animated: true, completion: nil)
                      }
                      

                      斯威夫特 5

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 2016-04-02
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        相关资源
                        最近更新 更多