【问题标题】:Get input value from TextField in iOS alert in Swift在 Swift 的 iOS 警报中从 TextField 获取输入值
【发布时间】:2014-12-21 10:36:54
【问题描述】:

我正在尝试使用输入发出警报消息,然后从输入中获取值。我发现了很多很好的教程如何制作输入文本字段。但我无法从警报中获取值。

【问题讨论】:

  • iOS 上的动作警报?
  • @AndyIbanez 是的,没提到!

标签: ios xcode swift input uialertcontroller


【解决方案1】:

为 Swift 3 及更高版本更新:

//1. Create the alert controller.
let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)

//2. Add the text field. You can configure it however you need.
alert.addTextField { (textField) in
    textField.text = "Some default text"
}

// 3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
    let textField = alert.textFields![0] // Force unwrapping because we know it exists.
    print("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.present(alert, animated: true, completion: nil)

斯威夫特 2.x

假设您想要在 iOS 上发出操作警报:

//1. Create the alert controller.            
var alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .Alert)

//2. Add the text field. You can configure it however you need.
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
    textField.text = "Some default text."
})

//3. Grab the value from the text field, and print it when the user clicks OK. 
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { [weak alert] (action) -> Void in
    let textField = alert.textFields![0] as UITextField
    println("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.presentViewController(alert, animated: true, completion: nil)

【讨论】:

  • 没问题。如果对您有帮助,请记住将其标记为已接受。谢谢!
  • 嗨@AndyIbanez我正在尝试在我的应用程序上实现你的代码,但是它指出错误“使用未声明的标识符var”我是Xcode的新手,所以如果这是一个基本错误,我深表歉意我的代表
  • @Sjharrison 我的代码是为 Swift 编写的。我能想到的唯一原因会让你对var 关键字感到麻烦,因为你是用Objective-C 编写的。
  • 谁能解释为什么[weak alert]?我在看 Swift 3。
  • 对于步骤 3 中的 Swift 3 警报。是可选的,需要 "?" let textField = alert?.textFields![0] // Force unwrapping because we know it exists.print("Text field: \(textField?.text)")
【解决方案2】:

斯威夫特 5

为方便起见,您可以使用以下扩展程序。

ViewController 内使用:

showInputDialog(title: "Add number",
                subtitle: "Please enter the new number below.",
                actionTitle: "Add",
                cancelTitle: "Cancel",
                inputPlaceholder: "New number",
                inputKeyboardType: .numberPad, actionHandler:
                        { (input:String?) in
                            print("The new number is \(input ?? "")")
                        })

扩展代码:

extension UIViewController {
    func showInputDialog(title:String? = nil,
                         subtitle:String? = nil,
                         actionTitle:String? = "Add",
                         cancelTitle:String? = "Cancel",
                         inputPlaceholder:String? = nil,
                         inputKeyboardType:UIKeyboardType = UIKeyboardType.default,
                         cancelHandler: ((UIAlertAction) -> Swift.Void)? = nil,
                         actionHandler: ((_ text: String?) -> Void)? = nil) {
        
        let alert = UIAlertController(title: title, message: subtitle, preferredStyle: .alert)
        alert.addTextField { (textField:UITextField) in
            textField.placeholder = inputPlaceholder
            textField.keyboardType = inputKeyboardType
        }
        alert.addAction(UIAlertAction(title: actionTitle, style: .default, handler: { (action:UIAlertAction) in
            guard let textField =  alert.textFields?.first else {
                actionHandler?(nil)
                return
            }
            actionHandler?(textField.text)
        }))
        alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler))
        
        self.present(alert, animated: true, completion: nil)
    }
}

【讨论】:

  • 请注意,如果您要呈现“添加”动作,请确保“默认”而不是“破坏性”的样式 - alert.addAction(UIAlertAction(title: actionTitle, style: .default 。 ..
  • @Gunhan 如何为文本字段分配委托?
  • @VaibhavJhaveri 只需向函数添加一个参数,例如委托:UITextFieldDelegate? = nil,并在我们添加文本字段的函数内部分配它,例如textField.delegate = 委托
  • @Gunhan 那行得通。但是,显示文本字段时它是第一响应者。我想把它关掉。我怎样才能做到这一点?我想在单击文本字段时打开自定义视图
【解决方案3】:

Swift5 和 Xcode 10

使用保存和取消操作添加两个文本字段并读取 TextFields 文本数据

func alertWithTF() {
    //Step : 1
    let alert = UIAlertController(title: "Great Title", message: "Please input something", preferredStyle: UIAlertController.Style.alert )
    //Step : 2
    let save = UIAlertAction(title: "Save", style: .default) { (alertAction) in
        let textField = alert.textFields![0] as UITextField
        let textField2 = alert.textFields![1] as UITextField
        if textField.text != "" {
            //Read TextFields text data
            print(textField.text!)
            print("TF 1 : \(textField.text!)")
        } else {
            print("TF 1 is Empty...")
        }

        if textField2.text != "" {
            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
    }

    //Step : 4
    alert.addAction(save)
    //Cancel action
    let cancel = UIAlertAction(title: "Cancel", style: .default) { (alertAction) in }
    alert.addAction(cancel)
    //OR single line action
    //alert.addAction(UIAlertAction(title: "Cancel", style: .default) { (alertAction) in })

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

}

更多解释https://medium.com/@chan.henryk/alert-controller-with-text-field-in-swift-3-bda7ac06026c

【讨论】:

  • 如何为文本字段分配委托?
【解决方案4】:

Swift 版本:5.+

在当前范围内创建一个新的TextField 变量并将其分配给alert.addTextField 完成处理程序中的alertTextField。在 UIAlertAction 完成处理程序中使用 textField 的值。

@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
          //Variable to store alertTextField
            var textField = UITextField()
            
            let alert = UIAlertController(title: "Add new item", message: "", preferredStyle: .alert)
            alert.addTextField { alertTextField in
                alertTextField.placeholder = "Create new item"
                
                //Copy alertTextField in local variable to use in current block of code
                textField = alertTextField
            }
            
            let action = UIAlertAction(title: "Add item", style: .default) { action in
                //Prints the alertTextField's value
                print(textField.text!)
            }
            
            alert.addAction(action)
            present(alert, animated: true, completion: nil)
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 2015-11-20
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    相关资源
    最近更新 更多