【问题标题】:Swift UIAlertController Getting Text Field TextSwift UIAlertController 获取文本字段文本
【发布时间】:2014-10-10 18:41:27
【问题描述】:

当按下输入按钮时,我需要从警报视图中的文本字段中获取文本。

func inputMsg() {

    var points = ""
    var outOf = ""

    var alertController = UIAlertController(title: "Input View", message: "Please Input Your Grade", preferredStyle: UIAlertControllerStyle.Alert)

    let actionCancle = UIAlertAction(title: "Cancle", style: UIAlertActionStyle.Cancel) { ACTION in

        println("Cacle")
    }
    let actionInput = UIAlertAction(title: "Input", style: UIAlertActionStyle.Default) { ACTION in

        println("Input")
        println(points)
        println(outOf)
    }

    alertController.addAction(actionCancle)
    alertController.addAction(actionInput)
    alertController.addTextFieldWithConfigurationHandler({(txtField: UITextField!) in
        txtField.placeholder = "I got"
        txtField.keyboardType = UIKeyboardType.NumberPad
        points = txtField.text
        })



    alertController.addTextFieldWithConfigurationHandler({(txtField: UITextField!) in
        txtField.placeholder = "Out Of"
        txtField.keyboardType = UIKeyboardType.NumberPad
        outOf = txtField.text
    })
    presentViewController(alertController, animated: true, completion: nil)
}

【问题讨论】:

    标签: xcode swift uialertcontroller


    【解决方案1】:

    根据要求,这是一个实施解决方案。

    alertController.addAction(UIAlertAction(title: "Submit", style: UIAlertActionStyle.Default,handler: {
                (alert: UIAlertAction!) in
                if let textField = alertController.textFields?.first as? UITextField{
                    println(textField.text)
                }
            }))
    

    如上所述,alertController 有一个名为textFields 的属性。如果您添加了一个文本字段,您可以有条件地打开该属性以安全地访问文本字段。在这种情况下,由于只有一个文本字段,我只是使用 first 属性进行了展开。希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      UIAlertController 有一个textFields 属性。那是它的文本字段。您的任何处理程序都可以检查它,因此可以从任何文本字段中获取文本。

      【讨论】:

      • 你会怎么做?我已经告诉了你所有要知道的事情。警报控制器是alertController。它的文本字段是textFields。他们的文字是他们的text。您已经创建了一个输入按钮,并为它提供了一个操作处理程序,该处理程序将在按下输入按钮时运行,并且您已经将日志消息放入其中以证明这一点。没有比这更简单的了。
      • @Unome 不要用我没有编写的代码来破坏我的帖子。我故意没有提供代码。如果您想用代码添加自己的答案,请随意这样做!这是完全合法的,并且比试图弄乱别人的答案要好得多的 Stack Overflow 行为。它对您有很多好处:您的答案可以得到支持; OP 甚至可能取消选中我的答案并检查你的答案!
      • @matt,对不起。您的回答是正确的,它帮助我解决了问题。我只是在 cmets 中添加了一个实现示例作为 requested
      • @Unome 不用道歉; Stack Overflow 需要一些时间来适应。说真的,我邀请您使用自己的代码添加自己的答案。但我宽恕的是你把话放在我的嘴里。
      • @matt 添加了单独的帖子
      猜你喜欢
      • 1970-01-01
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多