当用户点击按钮时,我导航到另一个 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/