【问题标题】:If/Else statement with UIKit Functions in SwiftSwift 中带有 UIKit 函数的 If/Else 语句
【发布时间】:2015-03-31 20:40:43
【问题描述】:

我正在想办法让我的 iOS 应用程序将屏幕截图保存到相机胶卷,然后弹出一个警报,告诉用户屏幕截图已成功保存。我能想到的唯一方法是使用某种形式的 if/else 循环(正如您将在下面的伪代码 cmets 中看到的那样),但我想不出任何语法可以与 UIKit 中的 UIImageWriteToSavedPhotosAlbum 函数一起使用.有什么建议吗?

func screenshotMethod()
{
    UIGraphicsBeginImageContextWithOptions(HighchartsView.scrollView.contentSize, false, 0);
    view.layer.renderInContext(UIGraphicsGetCurrentContext())
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    UIImageWriteToSavedPhotosAlbum(image, nil,nil, nil)
    //if saved to Camera Roll
    //            {
    //              confirmScreenshot()
    //            }
    //        
    //else 
    //        {
    //            exit code/stop 
    //        }


}


func confirmScreenshot()
{
    let alertController = UIAlertController(title: "Success", message: "This chart has been successfully saved to your Camera Roll.", preferredStyle: .Alert)
    let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
    alertController.addAction(defaultAction)

    presentViewController(alertController, animated: true, completion: nil)
}

【问题讨论】:

  • 您的问题会误导您尝试对问题的描述做什么。所以你想知道如何知道 UIImageWriteToSavedPhotosAlbum() 是否成功保存了一张图片?最好的方法是使用选择器参数并从您选择的选择器中获取 NSError 并检查它。答案here 对如何做到这一点有很好的指导(在 Objective-C 中,它很容易适应 Swift)。

标签: xcode swift uikit alert camera-roll


【解决方案1】:

reference documentation 你可以看到有一个completionTarget 和一个completionSelector,这是某种基本委托(因为它没有强制执行你的类必须遵守的某种协议,用作委托目标)。例如,您将在您的类中实现一个符合completionSelector 定义的指定签名的函数,然后将self 传递为completionTarget,并将您的函数名称传递为completionSelector

在你的情况下,这将是:

func screenshotMethod()
{
    UIGraphicsBeginImageContextWithOptions(HighchartsView.scrollView.contentSize, false, 0);
    view.layer.renderInContext(UIGraphicsGetCurrentContext())
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    UIImageWriteToSavedPhotosAlbum(image, self, "didSaveScreenshot:", nil)
}

func didSaveScreenshot(image: UIImage?, didFinishSavingWithError error: NSError?, contextInfo contextInfo: AnyObject?) 
{
    if let error = error {
        //Not successful
    } else {
        //Success
    }
}

注意:我没有对此进行测试,但它应该可以工作。唯一的问题是,我不知道如何将 void 指针从 Objective-C 移植到 Swift,所以大家可以在这里纠正我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    相关资源
    最近更新 更多