ios - 在ios中使用 block 设置View的背景图像?

标签 ios objective-c-blocks nsdata

当用户点击按钮时,我导航到另一个 View ,并为该 View 设置背景图像。但是该图像来自 URL。要转换为 NSData 格式需要一些时间。那么,我如何使用 block 来实现这一点.

我使用了下面的代码,但没有运气..

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [self setBackGroundImageView];
});


- (void)setBackGroundImageView {
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:sharedDelegate.fbAppScopeId]];

    dispatch_sync(dispatch_get_main_queue(), ^(void) {            
        if (imageData) {
            UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[self squareImageWithImage:[UIImage imageWithData:imageData] scaledToSize:CGSizeMake(100, 100)]];

            CGFloat ratio = backgroundView.frame.size.width/screenWidth;

            CGRect imageFrame = backgroundView.frame;
            imageFrame.size.width = screenWidth;
            imageFrame.size.height = backgroundView.frame.size.height/ratio;

            if (imageFrame.size.height<screenHeight) {
                ratio = backgroundView.frame.size.height/screenHeight;
                imageFrame.size.height = screenHeight;
                imageFrame.size.width = backgroundView.frame.size.width/ratio;
            }

            backgroundView.frame = imageFrame;
            backgroundView.center = CGPointMake(screenWidth/2, backgroundView.center.y);


            backgroundView.alpha = 0.5;
            [self.view addSubview:backgroundView];
        }
    }
}

最佳答案

您不能在主线程以外的其他线程上执行 UI 事件(添加或删除 View )。如果这样做,可能会出现错误。

如果您仍想这样做,请在主线程上添加 imageView 并在 block 中设置其图像。

附注您可以使用 block 预加载(在应用程序启动时)图像数据,完成后您可以将其用作 imageView.image=preLoadImage;

关于ios - 在ios中使用 block 设置View的背景图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30979187/

相关文章:

ios - block 的执行总是被延迟

swift - Facebook 图片格式?

ios - swift 警告 : A lonng-running operation is being executed on the main thread

ios - Firebase 应用程序配置失败的 IOS

objective-c-blocks - 在 iOS 上使用 Parse,如何在后台将两个 PFFiles 保存到一个 PFObject

ios - 为什么 FireBase 查询 block 中的 NSString 为 null?

iphone - 上传或导出大视频会占用内存并导致崩溃...我该如何分解它?

ios - AVAudioPlayer.initWithData 抛出异常

ios - 如何轻松分离存储在较大 NSString 中的一组字符串?

ios - 当 UITableViewCell 处于编辑模式并且我们重新加载 UITableView 时,即使在重新加载后如何保持该特定单元格处于编辑模式