how to avoid delay when adding more than one button to scrollview in iPhone?

不羁岁月 提交于 2019-12-12 02:27:06

问题


I need to add more than one button (its depend upon array count) to UIScrollview.Now i am using the following code.This code is working properly but more time ( delay for adding button) taking for this function.Please help me..

   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;
}

回答1:


Because you are loading your image from server so it blocks your main thread till image load itself completely. Try loading image in different thread

Below is an example that shows how to load image on diffrent thread

Add your button object and url in an array (this can be written inside your for loop)

 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;

now implement loadImage

-(void)loadImage:(NSArray *)objectArray
 {
    UIImageView *tempImageView = (UIImageView *)[objectArray objectAtIndex:0];
    tempImageView.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[objectArray objectAtIndex:1]]]];

 }



回答2:


For the ready made project you can use the following link. As you are loading images from server it should also make CACHE of the images , so as not to download images again and again, So, there should be something like lazyloading( this will not solve by just running in background)

LAZYLOADING scrollView




回答3:


Get SDWebImage from GitHub. There's a category in it called UIButton+WebCache which can load your button's images asynchronously as well as store them on disk and memory to speed up their subsequent reloads.

#import "UIButton+WebCache"

....
UIButton *button...
[button setImageWithURL:[NSURL urlWithString:@"www.etc.com/img.jpg"] forControlState:UIControlStateNormal];


来源:https://stackoverflow.com/questions/18486108/how-to-avoid-delay-when-adding-more-than-one-button-to-scrollview-in-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!