ios Swift 2:扩展 - 使用textfield进行警报

时间:2016-09-01 09:54:24

标签: ios swift uitextfield uialertcontroller

我正在尝试使用带有文本字段的uialertcontroller使用扩展名uialertcontroller创建一个函数

这是我的代码:

extension UIAlertController{

class func AlertWithTextField(here: String, message1 : String) -> UIAlertController{

    var alertController:UIAlertController?
    alertController = UIAlertController(title: here,
        message: message1,
        preferredStyle: .Alert)

    alertController!.addTextFieldWithConfigurationHandler(
        {(textField: UITextField!) in
            textField.placeholder = "Ex: 1"
            textField.textAlignment = .Center
            textField.delegate = self
            textField.keyboardType = UIKeyboardType.NumberPad
    })
    let action = UIAlertAction(title: "Submit",
        style: UIAlertActionStyle.Default,
        handler: {[weak self]
            (paramAction:UIAlertAction!) in
            if let textFields = alertController?.textFields{
                let theTextFields = textFields as! [UITextField]
                let enteredText = theTextFields[0].text
                print("\n\(enteredText)") }
        })
    let action2 =  UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
    alertController?.addAction(action)
    alertController?.addAction(action2)

}}
好吧,我对“自我”这个词有疑问,我找不到他们的解决方案,这个问题的解决方案可能是什么?

1 个答案:

答案 0 :(得分:0)

对于你的第一个自我问题,我建议你做这样的事情

    class func AlertWithTextField(here: String, message1 : String, delegate:UITextFieldDelegate?) -> UIAlertController{

    var alertController:UIAlertController?
    alertController = UIAlertController(title: here,
                                        message: message1,
                                        preferredStyle: .Alert)

    alertController!.addTextFieldWithConfigurationHandler(
        {(textField: UITextField!) in
            textField.placeholder = "Ex: 1"
            textField.textAlignment = .Center
            textField.delegate = delegate
            textField.keyboardType = UIKeyboardType.NumberPad
    })
    let action = UIAlertAction(title: "Submit",
                               style: UIAlertActionStyle.Default,
                               handler: {(paramAction:UIAlertAction!)->Void in
                                if let textFields = alertController?.textFields {
                                    let theTextFields = textFields
                                    let enteredText = theTextFields[0].text
                                    print("\n\(enteredText)") }
        })
    let action2 =  UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
    alertController?.addAction(action)
    alertController?.addAction(action2)
    return alertController!
}

您可以在静态方法中接受UITextFieldDelegate对象并将其分配给委托,对于第二个问题,您声明弱自我但不在闭包中使用它,所以只需删除它,您的代码应该可以正常工作。