Align TextView to right programmatically in TableViewCell - ios

i can not align to the right a texview in a Custom TableViewCell.
I tried with NSTextAlignmentRight but simply doesn't work.
I adjust all the layout programmatically, maybe i forgot some checkbox to uncheck in my storyboard.
Sorry for my english, y hope you understand!
Here's my code inside cellForRowAtIndexPath:
cell = [self.tablaChat dequeueReusableCellWithIdentifier:simpleTableIdentifierUser];
if (cell == nil) {
cell = [[ChatTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifierUser];
}
cell.mensajeUsuario2.text = [NSString stringWithFormat:#"%#", [[self.dict_mensajes valueForKey:#"mensaje"] objectAtIndex:indexPath.row]];
NSString *dateAsString = [[self.dict_mensajes valueForKey:#"timestamp"] objectAtIndex:indexPath.row];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [formatter dateFromString:dateAsString];
//[self convertirFecha:date];
cell.labelUsuario2.text = [NSString stringWithFormat:#"%# el %#", [[self.dict_mensajes valueForKey:#"nombre"] objectAtIndex:indexPath.row], [self convertirFecha:date]];
cell.mensajeUsuario2.frame = CGRectMake(cell.mensajeUsuario2.frame.origin.x,
cell.mensajeUsuario2.frame.origin.y,
self.view.frame.size.width - cell.imagenUsuario2.frame.size.width - 25,
cell.mensajeUsuario2.frame.size.height);
cell.imagenUsuario2.frame = CGRectMake(self.view.frame.size.width - cell.imagenUsuario2.frame.size.width - 10,
cell.imagenUsuario2.frame.origin.y,
cell.imagenUsuario2.frame.size.width,
cell.imagenUsuario2.frame.size.height);
CGFloat fixedWidth = cell.mensajeUsuario2.frame.size.width;
CGSize newSize = [cell.mensajeUsuario2 sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
CGRect newFrame = cell.mensajeUsuario2.frame;
newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
cell.mensajeUsuario2.frame = newFrame;
cell.mensajeUsuario2.scrollEnabled = NO;
[cell.mensajeUsuario2.layer setBorderWidth: 1.0];
[cell.mensajeUsuario2.layer setCornerRadius:8.0f];
[cell.mensajeUsuario2.layer setMasksToBounds:YES];
alturaCelda = cell.mensajeUsuario2.frame.size.height + cell.labelUsuario2.frame.size.height;
cell.mensajeUsuario2.backgroundColor = Rgb2UIColorMediumLight(0, 0, 0);
cell.mensajeUsuario2.textColor = Rgb2UIColorMask(255, 255, 255);
cell.labelUsuario2.frame = CGRectMake(cell.labelUsuario2.frame.origin.x,
alturaCelda - 10,
self.view.frame.size.width - cell.imagenUsuario2.frame.size.width - 30,
cell.labelUsuario2.frame.size.height);
NSString *urlImagen = [NSString stringWithFormat:#"%#", [[self.dict_mensajes valueForKey:#"foto"] objectAtIndex:indexPath.row]];
NSURL *imageURL = [NSURL URLWithString:urlImagen];
UIImage *image;
// 1. Check the image cache to see if the image already exists. If so, then use it. If not, then download it.
if ([[ImageCache sharedImageCache] DoesExist:urlImagen] == true)
{
image = [[ImageCache sharedImageCache] GetImage:urlImagen];
cell.imagenUsuario2.image = image;
}
else
{
dispatch_async(kBgQueue, ^{
NSData *imgData = [NSData dataWithContentsOfURL: imageURL];
if (imgData) {
UIImage *image2 = [UIImage imageWithData:imgData];
if (image2) {
dispatch_async(dispatch_get_main_queue(), ^{
ChatTableViewCell *updateCell = (id)[tableView cellForRowAtIndexPath:indexPath];
if (updateCell)
updateCell.imagenUsuario2.image = image2;
// Add the image to the cache
[[ImageCache sharedImageCache] AddImage:urlImagen :image2];
});
}
}
});
}
[cell.mensajeUsuario2 sizeToFit];
[cell.mensajeUsuario2 layoutIfNeeded];
cell.mensajeUsuario2.textAlignment = NSTextAlignmentRight;

I solved in this way:
i moved the "cell.mensajeUsuario2.frame" declaration to the bottom and i change it to this.
cell.mensajeUsuario2.frame = CGRectMake(cell.imagenUsuario2.frame.origin.x - 10 - cell.mensajeUsuario2.frame.size.width,
cell.mensajeUsuario2.frame.origin.y,
cell.mensajeUsuario2.frame.size.width,
cell.mensajeUsuario2.frame.size.height);

Related

How to zoom and swipe multiple images coming from webservise in objective c

1) In my application, I want to zoom and pinch an image. In xib file, there is a imageView inside a scrollview.Page control is used for swiping images. For a single image it gets zoomed, but for multiple images(coming from web service) it is not getting swipe and zoom.
In setMultipleImages method, images are not getting zoomed and swiped, while if image is single it gets zoom properly.
2) In UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]]; line code, want to replace uiimage with uiimageview. How can I do it?
My code is:
-(void)setMultipleImages{
for (int i = 0; i < [imageMArray count]; i++){
NSString *logoName;
NSArray *imageNameArray = [[imageMArray objectAtIndex:i] componentsSeparatedByString:#"/"];
logoName = [[NSString alloc]initWithFormat:#"%#",[imageNameArray lastObject]];
if (![[AppDelegateHelper getInstance] fileExist:logoName])
{
NSString *imageURL = [[NSString alloc]initWithFormat:#"%#%#",[UrlBuilder getWebsiteUrl],[imageMArray objectAtIndex:i]];
[self startProcessing];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]];
[activityIndicator stopAnimating];
DebugLog(#"%f,%f",image.size.width,image.size.height);
NSArray *docDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [docDir objectAtIndex:0];
DebugLog(#"saving png");
NSString *pngFilePath = [NSString stringWithFormat:#"%#/%#",cacheDirectory,[imageNameArray lastObject]];
NSData *data1 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];
[data1 writeToFile:pngFilePath atomically:YES];
}
}
[self loadImageData];
}
-(void)loadImageData
{
int X =0;
for (int s=0; s<imageMArray.count; s++) {
NSString *logoName;
NSArray *imageNameArray = [[imageMArray objectAtIndex:s] componentsSeparatedByString:#"/"];
logoName = [[NSString alloc]initWithFormat:#"%#",[imageNameArray lastObject]];
if([[AppDelegateHelper getInstance] loadImage:logoName] != nil)
{
// UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake(X, 0, scrollView.frame.size.width, 300)] ;
[imageView setImage:[[AppDelegateHelper getInstance] loadImage:logoName]];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[scrollView addSubview: imageView];
X = X + imageView.frame.size.width;
}
else
{
//UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake(X, 0, scrollView.frame.size.width, 300)] ;
[imageView setImage:[UIImage imageNamed:#"NoImage.png"]];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[scrollView addSubview: imageView];
X = X + imageView.frame.size.width;
}
}
self.pageControl.numberOfPages = [imageMArray count];
scrollView.contentSize = CGSizeMake(X,scrollView.frame.size.height);
lblCount.text = [[NSString alloc]initWithFormat:#"1 sur %lu",(unsigned long)imageMArray.count];
}
Add all your images to imageview. Then apply pinchguesture to images view for zoom effect.
Pinch Guesture:
UIPinchGestureRecognizer *imageviewguesture=[[UIPinchGestureRecognizer alloc]initWithTarget:self action:#selector(ImageViewPinchGuesture:)];
add pinch guesture to your image view:
[YourImageView addGestureRecognizer:imageviewguesture];
Make your selector method:
-(void)ImageViewPinchGuesture:(UIPinchGestureRecognizer *)pinGuestureregonizer{
pinGuestureregonizer.view.transform = CGAffineTransformScale(pinGuestureregonizer.view.transform, pinGuestureregonizer.scale, pinGuestureregonizer.scale);
pinGuestureregonizer.scale = 1;
}
In your .h file add this line
-(void)ImageViewPinchGuesture:(UIPinchGestureRecognizer *)pinGuestureregonizer;
To check effect in simulator Press Cmd+alt then press left mouse pad button and drag.
Hope this will Help. Don't forget to accept the answer if it helps you.

UIScrollView swipe with timer in iOS

I have the following code that render scroll view inside table view with three pages, I want the pages to be changed each 5 seconds , how can I do that ?
UITableViewCell *cell;
cell = [tableView dequeueReusableCellWithIdentifier: sliderIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sliderIdentifier];
}
if (sliderItems != nil && sliderItems.count > 0) {
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0,self.view.frame.size.width, 200)];
scroll.scrollEnabled = YES;
for (int i = 0; i < sliderItems.count ; i++) {
CGFloat xOrigin = i * self.view.frame.size.width;
UIImageView *awesomeView = [[UIImageView alloc] initWithFrame:CGRectMake(xOrigin, 0, self.view.frame.size.width, 200)];
ItemResponse *test = [ItemResponse new];
test = sliderItems[i];
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//this will start the image loading in bg
dispatch_async(concurrentQueue, ^{
NSString *urlStr = test.listingImage;
NSURL *imageUrl = [NSURL URLWithString:urlStr];
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
//this will set the image when loading is finished
dispatch_async(dispatch_get_main_queue(), ^{
awesomeView.image = [UIImage imageWithData:imageData];
[scroll addSubview:awesomeView];
UILabel *iconAdLabel = [[UILabel alloc]init];
iconAdLabel.frame = CGRectMake(0 + (i * self.view.frame.size.width),130,self.view.frame.size.width,70);
iconAdLabel.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
NSString *titleStr = [NSString stringWithFormat:#" %# ", test.listingTitle];
iconAdLabel.text = titleStr;
UIColor *color = [self getUIColorObjectFromHexString:#"#000000" alpha:0.6];
iconAdLabel.backgroundColor = color;
UIColor *textcolor = [self getUIColorObjectFromHexString:#"#ffffff" alpha:1.0];
iconAdLabel.textColor = textcolor;
iconAdLabel.textAlignment = NSTextAlignmentRight;
UIFont *font=[UIFont fontWithName:#"NotoKufiArabic" size:14.0f];
iconAdLabel.font = font;
iconAdLabel.numberOfLines = 2;
[scroll addSubview:iconAdLabel];
});
});
}
scroll.contentSize = CGSizeMake(self.view.frame.size.width * sliderItems.count , 200);
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//this will start the image loading in bg
dispatch_async(concurrentQueue, ^{
dispatch_async(dispatch_get_main_queue(), ^{
[self.view addSubview:scroll];
});
});
}
return cell;
You can use a NSTimer object
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:#selector(timerAction) userInfo:nil repeats:YES];
with action
-(void)timerAction
{
[scroll scrollRectToVisible:CGRectMake(x, y, width, height) animated:YES];
}
Also you need to invalidate the timer Object when the ViewController Disappears. So if you have multiple cells , use an NSArray to keep track of the timer objects and invalidate when no longer needed [timer invalidate]

UILabel not displaying after iOS 8.0 upgrade

Just updated to iOS 8.0 this morning. I have a piece of code which created some labels and displays them on the scree next to some images. It was working fine before the update. Now the label and the image is not displaying. Can some one please help as I have tried everything I can think of and nothing has solved my issue and couldn't find anyone else with a similar issue. Code attached below.
UIView *labelView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, kCategoryLabelHieght)];
labelView.backgroundColor = [self colorWithHexString:#"2D2D2D"];
UILabel *categoryTitle = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, 200, kCategoryLabelHieght)];
categoryTitle.textAlignment = NSTextAlignmentLeft;
categoryTitle.text = text;
categoryTitle.font = [UIFont fontWithName:#"HelveticaNeue" size:14];
codeAppDelegate *appDelegate = (codeAppDelegate *)[[UIApplication sharedApplication] delegate];
NSArray *fetchedCategory = [appDelegate getCategoryByName:text];
UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(10, 2, 20, 20)];
if(fetchedCategory.count)
{
for (int t=0; t<fetchedCategory.count; t++) {
Dealcategory_List *catList = [fetchedCategory objectAtIndex:t];
NSString *titleImage = [self URLEncodeString:[NSString stringWithFormat:#"%#",catList.image]];
NSURL *url = [NSURL URLWithString:titleImage];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *imgTabs = [UIImage imageWithData:data];
// [header2 setImage:imgTabs forState:UIControlStateNormal];
[imgTabs resizableImageWithCapInsets: UIEdgeInsetsMake(5, 10, 2, 0) resizingMode: UIImageResizingModeTile];
img.image= imgTabs;
}
}
else
{
NSArray *fetchedNewsCategory = [appDelegate getNewsCategoryByName:text];
if(fetchedNewsCategory.count > 0)
{
for (int t=0; t<fetchedNewsCategory.count; t++) {
News_Categories *catList = [fetchedNewsCategory objectAtIndex:t];
NSString *titleImage = [self URLEncodeString:[NSString stringWithFormat:#"%#",catList.category_image]];
NSURL *url = [NSURL URLWithString:titleImage];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *imgTabs = [UIImage imageWithData:data];
// [header2 setImage:imgTabs forState:UIControlStateNormal];
[imgTabs resizableImageWithCapInsets: UIEdgeInsetsMake(10, 10, 2, 0) resizingMode: UIImageResizingModeTile];
img.image= imgTabs;
}
}
else
{
NSArray *fetchedCompetition = [appDelegate getCompetitionByName:text];
if(fetchedCompetition.count > 0)
{
for (int t=0; t<fetchedCompetition.count; t++) {
Competitions_List *catList = [fetchedCompetition objectAtIndex:t];
NSString *titleImage = [self URLEncodeString:[NSString stringWithFormat:#"%#",catList.competition_tab_image]];
NSURL *url = [NSURL URLWithString:titleImage];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *imgTabs = [UIImage imageWithData:data];
// [header2 setImage:imgTabs forState:UIControlStateNormal];
[imgTabs resizableImageWithCapInsets: UIEdgeInsetsMake(10, 10, 2, 0) resizingMode: UIImageResizingModeTile];
img.image= imgTabs;
break;
}
}
}
}
categoryTitle.textColor = color;
[labelView addSubview:img];
[labelView addSubview:categoryTitle];
[self.contentView addSubview:labelView];
UIView *labelView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, kCategoryLabelHieght)];
You are defining a UIView but allocating a UILabel. iOS 8 is less tolerant to errors like this. Try to change it to
UIView *labelView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, kCategoryLabelHieght)];

How to Multiple UIImages cropping and saving in a single loop

In my project is using maximum 60 images and One of my feature is needs to be an automatically crop all the 60 images in a given Ratio. I'm using the for loop for this implementation.
Inside the for loop contains crop and save the images. It was Implemented. But My app Meets crash in device because of Due to Memory pressure. Please Help Me
for (int ref=0; ref<[_selectedPhotosCollectionthumb count];ref++)
{
UIScrollView *scrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0,biManager.screenSize.height/2,biManager.screenSize.width,biManager.screenSize.height/2)];
[scrollView setDelegate:self];
[scrollView setBackgroundColor:[UIColor clearColor]];
[self addSubview:scrollView];
// scrollView.backgroundColor=[UIColor blueColor];
scrollView.userInteractionEnabled=YES;
scrollView.scrollEnabled=YES;
scrollView.tag=ref;
scrollView.hidden=YES;
[_scrollViews addObject:scrollView];
NSLog(#"%i",[_selectedPhotosCollection count]);
NSMutableArray *arrayCell=[_productCollectionsDict valueForKey:[_selectedPhotosCollection objectAtIndex:ref]];
int heightV=0;
for (int cellIndex=0;cellIndex<[arrayCell count];cellIndex++)
{
PrintCellView *cellObj=[arrayCell objectAtIndex:cellIndex];
if(cellObj.pCount>0)
{
PrintEditCellView *cell;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
cell=[[PrintEditCellView alloc] initWithFrame:CGRectMake(0,heightV*100,biManager.screenSize.width,100)];
scrollView.contentSize=CGSizeMake(0,heightV*100+100);
cell.delegate=self;
}
else
{
cell=[[PrintEditCellView alloc] initWithFrame:CGRectMake(0,heightV*50,biManager.screenSize.width,50)];
scrollView.contentSize=CGSizeMake(0,heightV*50+50);
cell.delegate=self;
}
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"hh:mm:ss";
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSLog(#"The Current Time is %#",[dateFormatter stringFromDate:now]);
// NSData *imageData=UIImageJPEGRepresentation(Thumbimage,1.0);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:[_selectedPhotosCollection objectAtIndex:ref]];
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:path];
UIImage *image1=[[UIImage alloc]initWithData:data];
cell.productName.text=cellObj.productName.text;
UIImage * image=[self imageByCropping:image1 CropRatio:cell.productName.text];
NSLog(#"CROPPPP");
NSData *imageData= [[NSData alloc] initWithData:UIImageJPEGRepresentation(image,1.0)];
//
NSString* path1 = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"Prydex%i%#.jpg",cellIndex,[dateFormatter stringFromDate:now]]];
NSLog(#"pthhh:%#",path1);
[imageData writeToFile:path1 atomically:YES];
cell.editedImageURL=path1;
NSLog(#"%#,%i",cellObj.productName.text,cellObj.pCount);
[scrollView addSubview:cell];
[cell release];
heightV=heightV+1;
[dateFormatter release];
[image1 release];
// [imageData release];
// [image release];
}
}
//NSLog(#"Scroll Count %i",[_scrollViews count]);
for (UIScrollView *scrollView in _scrollViews)
{
if (scrollView.tag==0)
{
scrollView.hidden=NO;
}
else
{
scrollView.hidden=YES;
}
}
[SVProgressHUD dismiss];
}
Cropping Code
- (UIImage *)imageByCropping:(UIImage *)image CropRatio:(NSString*)ratio
{
CGSize size;
NSArray *array=[ratio componentsSeparatedByString:#"*"];
NSString *productWidth=[array objectAtIndex:0];
NSString *productHeight=[array objectAtIndex:1];
NSLog(#"SIZE:%#,%#",productWidth,productHeight);
NSLog(#"SIZE:%f,%f",image.size.width,image.size.height);
if (image.size.width/[productWidth intValue]>=230)
{
if (image.size.height/[productHeight intValue]>=230) {
size=CGSizeMake([productWidth intValue]*230,[productHeight intValue]*230);
NSLog(#"SIZE Inner:%i,%i",[productWidth intValue],[productHeight intValue]);
}
else if(image.size.width/[productWidth intValue]>=100)
{
if (image.size.height/[productHeight intValue]>=100)
{
size=CGSizeMake([productWidth intValue]*100,[productHeight intValue]*100);
NSLog(#"SIZE outer:%i,%i",[productWidth intValue],[productHeight intValue] );
}
}
}
else if(image.size.width/[productWidth intValue]>=100)
{
if (image.size.height/[productHeight intValue]>=100)
{
size=CGSizeMake([productWidth intValue]*100,[productHeight intValue]*100);
NSLog(#"SIZE outer:%i,%i",[productWidth intValue],[productHeight intValue] );
}
}
NSLog(#"crop---->%#",NSStringFromCGSize(size));
double x = (image.size.width - size.width) / 2.0;
double y = (image.size.height - size.height) / 2.0;
CGRect cropRect = CGRectMake(x, y, size.width, size.height);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return cropped;
}
The solution might be using recursion:
Create a method that takes an array of images you need to process. Inside the method check if array count is zero.
If it is empty you should return, possibly doing some callback to notify the application your image processing is done.
If the array is not empty, take the first image from the array, do all the processing, then remove the first object from the array and call the same method with the new array missing that element. The call should be kind of
[self performSelector:#selector(methodName:) withObject:imageArray];
All together should look something like this:
- (void)processImages:(NSArray *)images {
if(images.count < 1) {
[self performSelectorOnMainThread:#selector(imageProcessingDone) withObject:nil waitUntilDone:NO];
}
else {
UIImage *toProcess = images[0];
NSMutableArray *newArray = [images mutableCopy];
[newArray removeObjectAtIndex:0];
//do the processing
[self performSelector:#selector(processImages:) withObject:newArray];
}
}

Loading images on scrollview using lazy loading

I am working on an app in which I need to load nearly 211 images in a scrollview.
What I was doing was I was converting the images in binary format (NSData) and saving them in core data. Then retrieving them and populating them on the scrollview.
it does work, but sometimes it does throw "Memory warning".
I learned that lazy loading is a way to achieve this. But, I am not totally aware of how it is done.
Like, loading 3 or 5 images ahead/back of the image visible currently on the scrollview.
Can any bode help me with a simple example, which would help me understand from scratch ? and would point me in the right direction.
Thank you for your time.
Well, it is not needed to store images into core data. Just take all image URLs into NSMutableArray and try to use following code as per your requirement.Hope this helps you.
Try this code -
friendsScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 470, 320, 100)];
friendsScrollView.contentSize = CGSizeMake([meetUPFrndNameArray count] * 95,50);
friendsScrollView.backgroundColor = [UIColor clearColor];
friendsScrollView.delegate = self;
[self.view addSubview:friendsScrollView];
int imageX = 25,imageY = 20;
int backImageX = 10, backImageY = 10;
int flag = 0;
for (int i = 0; i < [meetUPFrndPhotoArray count]; i++) {
flag ++;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = paths[0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:meetUPFrndPhotoArray[flag-1]];
UIImage *img1 = [UIImage imageWithContentsOfFile:savedImagePath];
if (!img1 || [UIImagePNGRepresentation(img1) length] <=0)
{
id path = meetUPFrndPhotoArray[flag-1];
path = [path stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSURL *url = [NSURL URLWithString:path];
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:url, [NSString stringWithFormat:#"%d", flag], nil];
[self performSelectorInBackground:#selector(loadImageInBackground:) withObject:arr];
UIImageView *frndBackgroundImage = [[UIImageView alloc] initWithFrame:CGRectMake(backImageX, backImageY, 80, 80)];
frndBackgroundImage.image = [UIImage imageNamed:#"friend_image_background.png"];
frndBackgroundImage.backgroundColor = [UIColor clearColor];
frndBackgroundImage.layer.borderWidth = 2.0;
frndBackgroundImage.layer.masksToBounds = YES;
frndBackgroundImage.layer.shadowOffset = CGSizeMake(0, 1);
frndBackgroundImage.layer.shadowOpacity = 1;
frndBackgroundImage.layer.shadowRadius = 1.2;
frndBackgroundImage.layer.cornerRadius = 5.0;
frndBackgroundImage.layer.borderColor = [[UIColor clearColor] CGColor];
[friendsScrollView addSubview:frndBackgroundImage];
UIImageView *friendImage = [[UIImageView alloc] initWithFrame:CGRectMake(imageX, imageY, 50, 50)];
friendImage.tag = flag;
friendImage.image = [UIImage imageNamed:#"ic_user.png"];
[friendsScrollView addSubview:friendImage];
}
else
{
UIImageView *frndBackgroundImage = [[UIImageView alloc] initWithFrame:CGRectMake(backImageX, backImageY, 80, 80)];
frndBackgroundImage.image = [UIImage imageNamed:#"friend_image_background.png"];
frndBackgroundImage.backgroundColor = [UIColor clearColor];
frndBackgroundImage.layer.borderWidth = 2.0;
frndBackgroundImage.layer.masksToBounds = YES;
frndBackgroundImage.layer.shadowOffset = CGSizeMake(0, 1);
frndBackgroundImage.layer.shadowOpacity = 1;
frndBackgroundImage.layer.shadowRadius = 1.2;
frndBackgroundImage.layer.cornerRadius = 5.0;
frndBackgroundImage.layer.borderColor = [[UIColor clearColor] CGColor];
[friendsScrollView addSubview:frndBackgroundImage];
UIImageView *friendImage = [[UIImageView alloc] initWithFrame:CGRectMake(imageX, imageY, 50, 50)];
friendImage.tag = flag-1;
friendImage.image = img1;
[friendsScrollView addSubview:friendImage];
}
backImageX = backImageX + 80 + 10;
backImageY = 10;
imageX = imageX + 50 + 25 + 15;
imageY = 20;
}
Here meetUPFrndPhotoArray contains image URLs.
And
For Downloading images in Background -
- (void) loadImageInBackground:(NSArray *)urlAndTagReference{
NSData *imgData = [NSData dataWithContentsOfURL:urlAndTagReference[0]];
UIImage *img = [[UIImage alloc] initWithData:imgData];
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:img, urlAndTagReference[1], nil];
[self performSelectorOnMainThread:#selector(assignImageToImageView:) withObject:arr waitUntilDone:YES];
}
For Assigning downloaded image to perticular imageView -
- (void) assignImageToImageView:(NSArray *)imgAndTagReference{
for (UIImageView *checkView in [friendsScrollView subviews] ){
if ([imgAndTagReference count] != 0) {
if ([checkView tag] == [imgAndTagReference[1] intValue]){
[checkView setImage:imgAndTagReference[0]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = paths[0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:meetUPFrndPhotoArray[[imgAndTagReference[1] intValue]-1]];
UIImage* imageToSave = [checkView image];
NSData *imageData = UIImagePNGRepresentation(imageToSave);
[imageData writeToFile:savedImagePath atomically:NO];
}
}
}
}
Let me know if this helps you.Thanks in advance.All the best.
Make use of delegate functions, content size and content inset properties of the scrollview
Checkout this library It's a generic UIScrollView that reuses it's subviews like UITableView does (there is a dataSource object which is used to configure scroll view subviews)

Resources