我正在尝试使用带有扩展名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)

}}


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

最佳答案

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

    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对象,然后将其分配给委托,对于第二个问题,您声明弱的self而不在闭包中使用它,因此只需删除该对象,代码就可以正常工作。

关于ios - ios Swift 2:扩展名-带有文本字段的警报,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39268331/

10-10 11:52