在耗时的操作之前,视图不会出现

时间:2016-08-11 17:56:09

标签: ios swift

我已在我的应用中实施了此指标:https://github.com/vincechan/SwiftLoadingIndicator

在这个加载微调器到来之后,我希望它一直旋转,只要我的操作持续。

在我的操作中,我对图像做了一些工作,然后将它们显示给用户,但每次点击"运行操作"按钮,应用程序冻结几秒钟,更新视图与结果,然后显示叠加微调器。 我尝试过像这样的异步调度:

 @IBAction func manipulateImage(sender: AnyObject) {
    dispatch_async(dispatch_get_main_queue(), {
                    LoadingOverlayView.show()
                }); 
       if let beginImage = CIImage(image: self.imageView.image!) {
                    var outputImage = OutputImage(sourceImage: beginImage)
    //apply CIFilters:
                    outputImage.applyFilter(FilterType.Grayscale)
                    outputImage.applyFilter(FilterType.Sepia)
                    outputImage.applyFilter(FilterType.Vignette)
                    outputImage.applyFilter(FilterType.Shadow)

                    let cgimg = self.imageContext.createCGImage(outputImage, fromRect: outputImage.extent)

                    self.imageView.image = UIImage(CGImage: cgimg)
    LoadingOverlayView.hide()
}

但它不起作用。在没有异步调度的情况下,正常的方法调用也完全相同。

1 个答案:

答案 0 :(得分:1)

您可能在UI线程上运行此代码。如果是这样,您可以按如下方式将操作分派到后台队列:

// we're already on the UI thread, so dispatch to a background queue
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
   // do your background operations ...
   if let beginImage = CIImage(image: self.imageView.image!) {
       var outputImage = OutputImage(sourceImage: beginImage)
       //apply CIFilters:
       outputImage.applyFilter(FilterType.Grayscale)
       outputImage.applyFilter(FilterType.Sepia)
       outputImage.applyFilter(FilterType.Vignette)
       outputImage.applyFilter(FilterType.Shadow)

       let cgimg = self.imageContext.createCGImage(outputImage, fromRect: outputImage.extent)

       // make sure to dispatch UI function back to main queue!
       dispatch_async(dispatch_get_main_queue(), {
               self.imageView.image = UIImage(CGImage: cgimg)

                LoadingOverlayView.hide()
            }); 
     }
});

// we're already on the UI thread, so show the overlay now
LoadingOverlayView.show()