簡體   English   中英

ios Swift 2:擴展名-帶有文本字段的警報

[英]ios Swift 2: extension - Alert with textfield

我正在嘗試使用帶有擴展名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而不在閉包中使用它,因此只需刪除該對象,代碼就可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM