我在UIScrollView中有一堆UIButton,每个UIButton都从URL中获取一个图像。什么是最简单的方式,以便异步加载图像?
例如,通常的方法是:
[button setImage:[UIImage imageWithData:data] forState:UIControlStateNormal];
但是这会阻止用户界面,我不希望它
答案 0 :(得分:2)
你可以试试这个
[self performSelectorInBackground:@selector(loadImag) withObject:nil];
在loadImage函数中,从url加载图像,然后将其指定给按钮。 我不确定这对你有用......因为我是客观C开发的初学者
答案 1 :(得分:0)
尝试使用NSInvocationOperation,为每个图像按钮发出同步请求...将按钮作为参数传递,我的意思是......
初始化操作队列(可能在init上):
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
启动每个按钮的操作调用...
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(getImageFromURL:)
object:[NSDictionary dictionaryWithObjectsAndKeys:@"http://getMyImage.com/resource.jpg", @"url", button, @"button", nil]];
[queue addOperation:operation];
[operation release];
这可以是您的getImageFromURL:
选择器
- (void) getImageFromURL:(NSDictionary*)dict
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSURL *url = [NSURL URLFromString:[dict objectForKey:@"url"]];
UIButton *button = [dict objectForKey:@"button"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
UIImage *image = [[UIImage alloc] initWithData:data];
// Finally set the button image and release image ...
[pool drain];
}
不要忘记dealloc上的发布队列......
希望这有帮助! :)
答案 2 :(得分:-1)
我想没关系,如果你在加载一张图片的时候阻止了?问题是你有很多?如果是这样,那么我会这样做(不需要线程):
#define DELAY 0.1 // you may set it to 0 as well
...
[self performSelector:@selector(setupButton:)
withObject:[NSNumber numberWithInt:0]
afterDelay:DELAY];
...
-(void)setupButton:(NSNumber*)count
{
UIButton *button = [self buttonFromMyScrollViewWithCount:count.intValue];
[button setImage:...];
if (count.intValue < self.numberOfButtonsInMyScrollView)
[self performSelector:@selector(setupButton:)
withObject:[NSNumber numberWithInt:count.intValue + 1]
afterDelay:DELAY];
}