执行选择器不在Swift中调用

时间:2017-08-31 05:53:37

标签: ios iphone swift

我创建了自定义类,用于显示需要在点击时执行的警报控制器和已定义的操作。当我从其他类调用该函数时,会显示警报,但是当我单击Okay按钮时,不会调用执行选择器。以下是这个功能。

VFSCCocoaUtils.sharedInstance.createCommonAlert(mainTitle: kNoSimCardTitle, mainMessage: kNoSimCardMessage, subTitle: kOkButtonTitle, callBackName: #selector(self.getName), completionHandler: {( alertView) in
    self.present(alertView, animated: true, completion: nil)
})


func createCommonAlert(mainTitle : String , mainMessage : String , subTitle : String, callBackName : Selector , completionHandler: @escaping (UIAlertController) -> ()) {

    let selector: Selector = callBackName
    let alertView = UIAlertController(title:mainTitle, message:mainMessage, preferredStyle: .alert)
    alertView.addAction(UIAlertAction.init(title: subTitle, style: .default, handler: { (alertView) in
        DispatchQueue.main.async {
            self.perform(selector)
        }
    }))
    DispatchQueue.main.async {
        completionHandler(alertView)
    }
}

1 个答案:

答案 0 :(得分:1)

选择器应该在它所属的类的实例上执行,而不是在另一个类上执行。您需要修改警报的创建,如下所示:

func createCommonAlert(mainTitle : String , mainMessage : String , subTitle : String, callBackName : Selector, instance: NSObject , completionHandler: @escaping (UIAlertController) -> ()) {

    let selector: Selector = callBackName
    let alertView = UIAlertController(title:mainTitle, message:mainMessage, preferredStyle: .alert)
    alertView.addAction(UIAlertAction.init(title: subTitle, style: .default, handler: { [weak instance](alertView) in
        DispatchQueue.main.async {
            instance?.perform(selector)
        }
    }))
    DispatchQueue.main.async {
        completionHandler(alertView)
    }
}

然后按如下方式调用:

VFSCCocoaUtils.sharedInstance.createCommonAlert(mainTitle: kNoSimCardTitle, mainMessage: kNoSimCardMessage, subTitle: kOkButtonTitle, callBackName: #selector(VFSCSettingsViewController.getName), instance: self, completionHandler: {( alertView) in
    self.present(alertView, animated: true, completion: nil)
})