我需要向UIScrollview添加多个按钮(它依赖于数组计数)。现在我正在使用以下代码。此代码工作正常,但更多时间(添加按钮的延迟)采用此功能。请帮助我..
for (int i=0; i< [imageArray count]; i++) {
NSURL *url = [NSURL URLWithString:[[imgArray objectAtIndex:i]objectForKey:@"url"]];
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
button1.frame = CGRectMake(xp, 0, 75, 75);
[button1 setImage:img forState:UIControlStateNormal];
[button1 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
button1.layer.borderColor = [UIColor whiteColor].CGColor;
button1.layer.borderWidth = 2.0;
[mScrollView addSubview:button1];
xp += button1.frame.size.width+15;
}
答案 0 :(得分:1)
因为您正在从服务器加载图像,所以它会阻止主线程直到图像完全加载。尝试在不同的线程中加载图像
下面是一个示例,说明如何在不同的线程上加载图像
将您的按钮对象和网址添加到数组中(可以在for循环中编写)
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:0];
[array addObject:cell.businessLogoImageView];
[array addObject:@"your Url"];
[NSThread detachNewThreadSelector:@selector(loadImage:) toTarget:self withObject:array];
[array release];
array = nil;
现在实现loadImage
-(void)loadImage:(NSArray *)objectArray
{
UIImageView *tempImageView = (UIImageView *)[objectArray objectAtIndex:0];
tempImageView.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[objectArray objectAtIndex:1]]]];
}
答案 1 :(得分:0)
对于现成项目,您可以使用以下链接。 当您从服务器加载图像时,它还应该对图像进行CACHE,以免一次又一次地下载图像, 所以,应该有类似延迟加载的东西(这不能通过在后台运行来解决)
答案 2 :(得分:0)
从GitHub获取SDWebImage。其中有一个名为UIButton + WebCache的类别,它可以异步加载按钮的图像,并将它们存储在磁盘和内存中,以加速后续的重新加载。
#import "UIButton+WebCache"
....
UIButton *button...
[button setImageWithURL:[NSURL urlWithString:@"www.etc.com/img.jpg"] forControlState:UIControlStateNormal];