sebi sebi - 13 days ago 7
iOS Question

How can I add images in a button to a table without slow loading

I have 2 ways of adding images to a table and, which is most efficient, and is there a better way? Both ways are place on top of a button with "layer object".

Aslo I notice that the table scrolls slowly in the simulator, will this slow scrolling possibly take place on a real phone? The only reason I see why is possibly because I haven;t related the button, but it could be something else related to memory, or drawing in each cell. I can't be because the images come from URL's right?

Here are the 2 ways I add each button to the table cell:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

[button setTitle:@"image.png" forState:UIControlStateNormal];

[[button titleLabel] setFont:[UIFont fontWithName:@"Helvetica-Bold" size:13]];

[button setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];

[button setBackgroundColor:[UIColor blackColor]];

UIImage *btn = [UIImage imageWithData:"png image from url"];

UIImage* newImage2 = [btn scaleToSize:CGSizeMake(280, 209.0)];

CGSize newSize = CGSizeMake(280, 209.0);

UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);

[newImage2 drawInRect:CGRectMake(0, 0, (newSize.width), (newSize.height))];

UIImage *newImage4 = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

[button setImage:newImage4 forState:UIControlStateNormal];

button.frame = CGRectMake(20.0, 50.0, 280, 255.0);


////////////////////////////////////////// Second Way below:

UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];

[button2 setTitle:@"photo.png" forState:UIControlStateNormal];

[[button2 titleLabel] setFont:[UIFont fontWithName:@"Helvetica-Bold" size:13]];

[button2 setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];

[button2 setBackgroundColor:[UIColor blackColor]];

UIImage *btnImage = [UIImage imageWithData:"png image from url"];

UIImageView *imageView2 = [[UIImageView alloc] initWithImage:btnImage];

imageView2.frame = CGRectMake(0, 0, 280, 209);

button2.frame = CGRectMake(20.0, 50.0, 280, 255.0);

[button2 addSubview:imageView2];

Answer

Here some of your images are coming from remote server. You should use lazy loading to load images from remote server. It will download image asynchronously and load image according to need. You can also use SDWebImage library which do this & also have caching mechanism. Using this library is very easy & straight forward. like:

 [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                      placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
Comments