显示AlertView后,从Function返回Bool值

时间:2016-03-30 14:04:23

标签: ios objective-c swift uialertview uialertaction

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

请注意,我使用了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

问题是如何从此警报视图返回bool值。

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)
}

2 个答案:

答案 0 :(得分:1)

您不会从警报视图中返回bool。你的"确定" UIAlertAction处理程序是您应该采取适当操作的地方。检查是否应打印文档然后打印。或者从那里调用一个方法来执行此操作。但是从处理程序中做到这一点。处理程序是您当前有评论的代码块" //执行一些核心数据工作......"

答案 1 :(得分:0)

试试这个:

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)
}