Ios UIAlertViewDelegate在单独的类中
Im定义了一个符合UIAlertViewDelegate的类,如下所示:Ios UIAlertViewDelegate在单独的类中,ios,swift,Ios,Swift,Im定义了一个符合UIAlertViewDelegate的类,如下所示: class PaymentAlert: NSObject, UIAlertViewDelegate { var orderId: Int! var items: [String] init(orderId: Int, items: [String]) { self.orderId = orderId self.items = items } fu
class PaymentAlert: NSObject, UIAlertViewDelegate {
var orderId: Int!
var items: [String]
init(orderId: Int, items: [String]) {
self.orderId = orderId
self.items = items
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
println(index)
}
}
然后,我在另一个类中执行以下操作:
var alertClass = PaymentAlert(orderId: orderId, items: items)
var alert = UIAlertView(title: "Payment declined", message: "Do you want to retry?", delegate: alertClass, cancelButtonTitle: "Cancel", otherButtonTitles: "Retry")
alert.show()
一切运行正常,除了clickedButtonIndex委托函数在我单击任何按钮时从未被调用,我尝试将委托设置为alertClass.self,但没有做多少
为什么clickedButtonIndex函数从未被调用?
UIAlertView
的委托属性是弱的
,因此您的PaymentAlert
实例在点击按钮之前被销毁
您必须在某个地方保留对PaymentAlert
实例的强引用,直到该警报被解除。您有没有保留强引用的示例?您尝试构建的构造并不是那么简单。如果在UIViewController
内创建UIAlertView
,则应将PaymentAlert
存储在变量中。---您还可以从UIAlertView
中对PaymentAlert
进行子类化,并将其自身设置为delegate
--但一般来说,将单独的警报类作为代理不是一个好的做法。显示警报视图的对象也应该是具有一致生命周期的代理。