How to add text input in alertview of ios 8?

前端 未结 9 2390
眼角桃花
眼角桃花 2020-12-07 16:46

I want to add text input in alert-view of ios 8. I know it was done using UIAlertController but not have any idea. How to do it ?

9条回答
  •  抹茶落季
    2020-12-07 17:08

    Here's handy method with submit/cancel and completion handler for text if inputted:

    /**
     Presents an alert controller with a single text field for user input
    
     - parameters:
        - title: Alert title
        - message: Alert message
        - placeholder: Placeholder for textfield
        - completion: Returned user input
     */
    
    func showSubmitTextFieldAlert(title: String,
                                  message: String,
                                  placeholder: String,
                                  completion: @escaping (_ userInput: String?) -> Void) {
    
        let alertController = UIAlertController(title: title,
                                                message: message,
                                                preferredStyle: .alert)
    
        alertController.addTextField { (textField) in
            textField.placeholder = placeholder
            textField.clearButtonMode = .whileEditing
        }
    
        let submitAction = UIAlertAction(title: "Submit", style: .default) { (action) in
            let userInput = alertController.textFields?.first?.text
            completion(userInput)
        }
    
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in
            completion(nil)
        }
    
        alertController.addAction(submitAction)
        alertController.addAction(cancelAction)
    
        present(alertController, animated: true)
    }
    

提交回复
热议问题