在实现我自己的委托时,不会调用UIAlertViewDelegate方法clickedButtonAtIndex

时间:2015-01-10 10:15:00

标签: ios swift uialertview uialertviewdelegate

我想从不同的ViewControllers弹出警报。因为我想要处理用户是否一致点击“确定”或“取消”,我决定实现自己的UIAlertViewDelegate并从我的UIViewController调用它。

问题是当我点击“确定”或“取消”时,将永远不会调用willDismissWithButtonIndex,didDismissWithButtonIndex和clickedButtonAtIndex。我知道我的委托正在被使用,因为当警报显示时会调用willPresentAlertView()和didPresentAlertView()。

以下是我的代表的代码:

import UIKit

class AlertViewDelegate: NSObject, UIAlertViewDelegate {
    func willPresentAlertView(alertView: UIAlertView) {
        println("will present")
    }

    func didPresentAlertView(alertView: UIAlertView) {
        println("did present")
    }

    func alertViewCancel(alertView: UIAlertView) {
        println("cancelled")
    }

    func alertView(alertView: UIAlertView, willDismissWithButtonIndex buttonIndex: Int) {
        println("will dismiss")
    }

    func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) {
        println("did dismiss")
    }

    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        println("clicked")
    }
}

这是我的ViewController的代码:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        var delegate = AlertViewDelegate()
        var alert = UIAlertView(title: "alert", message: "blah blah", delegate: delegate, cancelButtonTitle: "cancel", otherButtonTitles: "OK")
        alert.show()
    }

}

我做错了什么?

1 个答案:

答案 0 :(得分:4)

此变量'var delegate = AlertViewDelegate()'在作用域末尾取消分配 所以没有调用,尝试将delegate移动到属性

相关问题