如何在Swift中将TextField添加到UIAlertController

108

我正在尝试显示一个带有 UITextViewUIAlertController。当我添加以下代码时:

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

我遇到了一个Runtime错误:

致命错误:在解包可选值时意外发现为空

    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中呈现的。

我从这里下载了代码,它可以正常工作。我将那个方法复制并粘贴到我的代码中,但它却出错了。最后一行有self也没有影响。


你更喜欢使用 UITextField 还是 UITextView - benc
14个回答

216

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

16

解决方案:

Swift 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 的顺序是否正确?看起来“Second Name”会出现在“First Name”上面。 - benc

12

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

UITextFieldDelegate

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

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

7
如何在AlertView中添加textField?让我们简短明了地说一下。
这适用于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 成员向其添加文本字段。


5

在最新的苹果Swift 5.1.3版本中,使用带有UITextfieldUIAlertController

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

编程愉快!! :)


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 中,弹出一个带有两个文本框的警告框,并且读取文本框中的文本数据在所有视图之上呈现警告框
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")

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
        }

    })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接