如何在Swift中将TextField添加到UIAlertController


96

我正在尝试显示UIAlertController带有的UITextView。当我添加行时:

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

我收到一个Runtime错误:

致命错误:解开Optional值时意外发现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)

ViewController通过呈现在我的内部IBAction

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


UITextField,而不是UITextView
benc

Answers:


192

斯威夫特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)
}

23

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

11

因此,我开始检查看看我的代码和工作代码之间可能有什么不同。我注意到我的ViewController扩展了

UITextFieldDelegate

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

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

9

解:

斯威夫特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正确吗?似乎“第二名”将出现在“名字”上方。
benc

6

如何将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然后通过访问类的addTextField成员向其添加文本字段UIAlertController


4

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

3

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

3

在Swift 4.2和Xcode 10.1中

带有两个TextfieldsRead TextField文本数据的警报,在所有视图的顶部显示警报

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)

}

如果要在所有视图之上显示aleert。

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

1

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

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
        }

    })

1

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

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)

1

UIAlertControllerUITextfield在最新的苹果斯威夫特版本5.1.3

创建一个lazy 变量UIAlertController在你的UIViewController,添加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
    }
}

快乐编码!:)


0

迅捷5

第一类符合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)

谢谢


0
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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.