Return 显示 AlertView 后来自 Function 的布尔值

Return a Bool value from Function after showing AlertView

我基本上可以选择在我的应用程序中打印文档。现在不允许打印一些文档(除非指定了条件)。所以我正在使用代表。

请注意,我混合使用了 Objective CSwift

基本上我的打印代码如下:

if ([self.delegate respondsToSelector:@selector(shouldPrintDocument)]) {
        BOOL shouldPrint = [self.delegate shouldPrintDocument];
        NSLog(@"Should Print %d", shouldPrint);
        if (shouldPrint){
              //We will print here
        }
}

现在在 Swift 方面,我基本上需要做的是与用户确认他们是否要继续打印文档。所以,我使用了UIAlertController

问题是如何从这个警报视图中return一个布尔值。

func shouldPrintDocument() -> Bool {
    let alertController = UIAlertController(title:"Confirm Print",
        message: message,
        preferredStyle: UIAlertControllerStyle.Alert)

    let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {(action: UIAlertAction) -> Void in
        alertController.dismissViewControllerAnimated(true, completion: { _ in })
        return false 
    })
    alertController.addAction(cancelAction)
    let ok: UIAlertAction = UIAlertAction(title: "Confirm", style: .Default, handler: {(action: UIAlertAction) -> Void in
        alertController.dismissViewControllerAnimated(true, completion: { _ in })
        //Perform some core data work here, i.e., save a few things and return
        return true // This is where the issue comes in
    })

    alertController.addAction(ok)
    self.presentViewController(alertController, animated: true, completion: nil)
}

您 return 警报视图中没有布尔值。您的 "ok" UIAlertAction 处理程序是您应该采取适当行动的地方。在那里检查是否应该打印文档,然后打印它。或者从那里调用一个方法来执行此操作。但是从处理程序中进行。处理程序是您当前在其中注释“// 执行一些核心数据工作...”的代码块...

试试这个:

var isprint:BOOL = false

func shouldPrintDocument() -> Bool {
let alertController = UIAlertController(title:"Confirm Print",
    message: message,
    preferredStyle: UIAlertControllerStyle.Alert)

let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {(action: UIAlertAction) -> Void in
    alertController.dismissViewControllerAnimated(true, completion: { _ in })
    isprint = false
})
alertController.addAction(cancelAction)
let ok: UIAlertAction = UIAlertAction(title: "Confirm", style: .Default, handler: {(action: UIAlertAction) -> Void in
    alertController.dismissViewControllerAnimated(true, completion: { _ in })
    //Perform some core data work here, i.e., save a few things and return
    isprint = true// This is where the issue comes in
})

alertController.addAction(ok)
 self.presentViewController(alertController, animated: true, completion: nil)
}