gpt4 book ai didi

ios - 不关闭 View 的 UIAlertController 操作

转载 作者:行者123 更新时间:2023-11-30 12:26:43 27 4
gpt4 key购买 nike

我创建了一个 UIAlertController,其中包含一个文本字段和一个将验证码发送到用户电话号码的操作。但是,该操作也会关闭警报 Controller ,使用户无法输入验证码。有没有办法使警报操作不关闭警报 Controller ?

   let alertController = UIAlertController(title: "Verification", message: "a code has been sent to your phone number", preferredStyle: .alert)

let confirm = UIAlertAction(title: "Confirm", style: .default, handler: {
alert -> Void in
//verifies code
})

let resend = UIAlertAction(title: "Resend", style: .default, handler: {
alert -> Void in
//resends code
})

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

})

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

alertController.addAction(confirm)
alertController.addAction(resend)
alertController.addAction(cancelAction)

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

最佳答案

您可以使用UITextFieldDelegateisEnabled UIAlertAction的属性(property)达到预期的效果。

步骤:

  1. 您的类(class)应确认 UITextFieldDelegate
  2. 您的警报操作应声明为类级别属性
  3. 在显示警报之前禁用警报操作
  4. 配置文本字段并将 delegate 设置为您的类
  5. 实现 shouldChangeCharactersIn: 方法
  6. 如果文本长度大于所需长度,则启用警报操作,否则禁用警报操作

代码:

// Your Class should confirm to UITextFieldDelegate
class ViewController: UIViewController, UITextFieldDelegate
{
// Verify alert action, alert button that want to be disabled
var verifyAction : UIAlertAction!

// Shows the alert
@IBAction func showAlert(sender : UIButton)
{
let alert = UIAlertController(title: "Verify", message: "Please Enter the verification code to continue", preferredStyle: UIAlertControllerStyle.alert)
verifyAction = UIAlertAction(title: "Verify", style: UIAlertActionStyle.default) { (action) in
// Do verification and other stuffs
}

// Configures textfield properties and delegate
alert.addTextField { (textField) in
textField.placeholder = "Verification Code"
textField.delegate = self
}

// Disables the button
verifyAction.isEnabled = false
alert.addAction(verifyAction)
self.present(alert, animated: true, completion: nil)
}

// Textfield delegate method for observing the text change
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
// if text length is greater than 0 enables the button, else disables it
let existingText = textField.text as NSString?
if let replacedText = existingText?.replacingCharacters(in: range, with: string), replacedText.characters.count > 0
{
verifyAction.isEnabled = true
}
else
{
verifyAction.isEnabled = false
}
return true
}
}

注意:我在发布代码之前写了这个答案,因此它不是基于您在问题中提供的代码。这是一个通用答案,如果您希望我这样做,我会编辑答案。

关于ios - 不关闭 View 的 UIAlertController 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44108183/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com