I have this code in my project that creates UIButtons with labels and images with values coming from a web service.
- (void)getMoviePosterImages
{
for (int i = 0; i < [self.rowCount intValue]; i++)
{
NSArray *postersArray = [self.jsonMutableArray objectAtIndex:i];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[postersArray objectAtIndex:6]]] imageProcessingBlock:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image)
{
[moviePosterButton setBackgroundImage:image forState:UIControlStateNormal];
}
failure:nil];
[operation start];
}
}
Here's the code where I created the UILabels:
- (void)displayMovieTitlesAndFrames
{
int imageCount = [self.rowCount intValue];
int offset_x = 21;
int offset_y = 24;
for (int i = 0; i < imageCount; i++)
{
// compute x & y offset
if (i % 3 == 0)
{
offset_x = 21;
}
else if (i % 3 == 1)
{
offset_x = 115;
}
else
{
offset_x = 210;
}
whiteBackgroundLabel = [[[UILabel alloc] initWithFrame:CGRectMake(offset_x, offset_y, MOVIE_THUMBNAIL_W, MOVIE_THUMBNAIL_H)] autorelease];
whiteBackgroundLabel.backgroundColor = [UIColor whiteColor];
whiteBackgroundLabel.layer.cornerRadius = 3.0;
whiteBackgroundLabel.layer.borderColor = [[UIColor lightGrayColor] CGColor];
whiteBackgroundLabel.layer.borderWidth = 1.0;
[scrollview addSubview:whiteBackgroundLabel];
moviePosterButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
moviePosterButton.frame = CGRectMake(offset_x + 5, offset_y + 5, MOVIE_THUMBNAIL_W - 10, MOVIE_THUMBNAIL_H - 10);
moviePosterButton.backgroundColor = [UIColor clearColor];
[moviePosterButton setBackgroundImage:[UIImage imageNamed:#"placeholder.png"] forState:UIControlStateNormal];
moviePosterButton.tag = i;
[moviePosterButton addTarget:self
action:#selector(imageButtonPressed:)
forControlEvents:UIControlEventTouchUpInside];
[scrollview addSubview:moviePosterButton];
movieTitleLabel = [[[UILabel alloc] initWithFrame:CGRectMake(offset_x, offset_y + 143, 90, 20)] autorelease];
movieTitleLabel.backgroundColor = [UIColor whiteColor];
movieTitleLabel.layer.cornerRadius = 3.0;
movieTitleLabel.layer.borderColor = [[UIColor lightGrayColor] CGColor];
movieTitleLabel.layer.borderWidth = 1.0;
movieTitleLabel.font = [UIFont fontWithName:#"Helvetica" size:11.0];
movieTitleLabel.textColor = [UIColor darkGrayColor];
movieTitleLabel.textAlignment = UITextAlignmentCenter;
movieTitleLabel.numberOfLines = 1;
movieTitleLabel.text = [[self.jsonMutableArray objectAtIndex:i] objectAtIndex:1];
[scrollview addSubview:movieTitleLabel];
quickBuyButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
quickBuyButton.frame = CGRectMake(offset_x + 1 + (MOVIE_THUMBNAIL_W - QUICK_BUY_BUTTON_W - 2), offset_y - 1 + 2, QUICK_BUY_BUTTON_W, QUICK_BUY_BUTTON_H);
quickBuyButton.backgroundColor = [UIColor clearColor];
[quickBuyButton setBackgroundImage:QUICK_BUY_BUTTON forState:UIControlStateNormal];
quickBuyButton.tag = i;
[quickBuyButton addTarget:self
action:#selector(quickBuyButtonPressed:)
forControlEvents:UIControlEventTouchUpInside];
[scrollview addSubview:quickBuyButton];
// increment offset
if (offset_x == 210)
{
offset_y += 171;
}
}
if ((offset_x == 21) || (offset_x == 115))
{
offset_y += 171;
}
[self adjustScrollViewAndBackground:offset_y];
}
All my UIButtons are created with their respective tags and I want to put their images on each on those buttons. The code above works only on the last UIButton created. I want to populate all of my buttons with images using the code above. Can someone tell me where I'm getting it all wrong?
In your getMoviePosterImages method you are setting an image to the moviePosterButton which might be the last button you just created so this is normal if only the last button gets its image. You need either to retrieve each buttons by their tags or build an array with all you buttons so you can easily access them. You could maybe do something like that:
- (void)getMoviePosterImages
{
for (int i = 0; i < [self.rowCount intValue]; i++)
{
NSArray *postersArray = [self.jsonMutableArray objectAtIndex:i];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[postersArray objectAtIndex:6]]] imageProcessingBlock:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image)
{
[(UIButton *)buttonsArray[i] setBackgroundImage:image forState:UIControlStateNormal];
// or
// [(UIButton *)[self.view viewWithTag:i] setBackgroundImage:image forState:UIControlStateNormal];
}
failure:nil];
[operation start];
}
}
Hope this helps ;)
Related
What am I missing? The inner scrollview and the image view fill the entire screen. But somehow my image is not centered. The top left corner of the image starts in the center of the view, but I would like to have the image nicely centered. Also during zooming.
-(void)prepareScrollView
{
for(int i =0;i<[self.layoverPhotoAssets count];i++){
PHAsset *asset = self.layoverPhotoAssets[i];
FMImageZoomViewController *zoomController = [[FMImageZoomViewController alloc] init];
// UIImageView *imageView = [[UIImageView alloc] init];
int x = self.scrollView.frame.size.width * i;
zoomController.view.frame = CGRectMake(x, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height);
//zoomController.view.frame = CGRectMake(0,0,self.view.bounds.size.width,self.view.bounds.size.height);
[self.scrollView addSubview:zoomController.view];
zoomController.zoomScroller.delegate = self;
zoomController.imageView.tag = 1;
[self.zoomControllers addObject:zoomController];
PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
options.resizeMode = PHImageRequestOptionsResizeModeFast;
options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat; //I only want the highest possible quality
options.synchronous = NO;
options.networkAccessAllowed = YES;
[[PHImageManager defaultManager] requestImageForAsset:asset targetSize:zoomController.zoomScroller.frame.size contentMode:PHImageContentModeAspectFill options:options resultHandler:^(UIImage *result, NSDictionary *info) {
dispatch_async(dispatch_get_main_queue(), ^{
if(result){
zoomController.imageView.image = result;
zoomController.imageView.backgroundColor = [UIColor redColor];
}
});
}];
//self.scrollView.contentSize= ;
}
[self.scrollView setContentSize:CGSizeMake(self.scrollView.frame.size.width * [self.layoverPhotoAssets count], 0)];
[self scrollToAsset:self.selectedAsset];
}
Consider:
zoomController.view.frame = CGRectMake(x, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height);
[self.scrollView addSubview:zoomController.view];
That cannot be right. If zoomController.view is to be a subview of self.scrollView, its frame within self.scrollView is in terms of the bounds of self.scrollView, not the frame of self.scrollView.
Solved it like this:
-(void)prepareScrollView
{
for(int i =0;i<[self.layoverPhotoAssets count];i++){
PHAsset *asset = self.layoverPhotoAssets[i];
FMImageZoomViewController *zoomController = [[FMImageZoomViewController alloc] init];
// UIImageView *imageView = [[UIImageView alloc] init];
int x = self.scrollView.frame.size.width * i;
zoomController.view.frame = CGRectMake(x, 0, self.scrollView.bounds.size.width, self.scrollView.bounds.size.height);
//zoomController.view.frame = CGRectMake(0,0,self.view.bounds.size.width,self.view.bounds.size.height);
[self.scrollView addSubview:zoomController.view];
zoomController.zoomScroller.delegate = self;
[self.zoomControllers addObject:zoomController];
PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
options.resizeMode = PHImageRequestOptionsResizeModeExact;
options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat; //I only want the highest possible quality
options.synchronous = NO;
options.networkAccessAllowed = YES;
[[PHImageManager defaultManager] requestImageForAsset:asset targetSize:zoomController.zoomScroller.bounds.size contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage *result, NSDictionary *info) {
dispatch_async(dispatch_get_main_queue(), ^{
if(result){
zoomController.imageView = [[UIImageView alloc] initWithImage:result];
zoomController.imageView.frame = zoomController.zoomScroller.bounds;
[zoomController.imageView setContentMode:UIViewContentModeScaleAspectFit];
zoomController.imageView.clipsToBounds = YES;
[zoomController.imageView setCenter: self.scrollView.center];
zoomController.imageView.tag = 1;
[zoomController.zoomScroller addSubview:zoomController.imageView];
// zoomController.imageView.contentMode = UIViewContentModeCenter;
// if (zoomController.imageView.bounds.size.width > result.size.width && zoomController.imageView.bounds.size.height > result.size.height) {
// zoomController.imageView.contentMode = UIViewContentModeScaleAspectFit;
// }
}
});
}];
//self.scrollView.contentSize= ;
}
[self.scrollView setContentSize:CGSizeMake(self.scrollView.frame.size.width * [self.layoverPhotoAssets count], 0)];
[self scrollToAsset:self.selectedAsset];
}
Name count i get after parsing json is random i.e. it can display any number of values ranging from 1 to 100. I created that many number of labels as shown in the code below, but only the last iterated value is displayed in the label when i pass NSString *name to putLabelsInScrollView method. Can any one help me out to fix this logic to display different name in different created labels? I cannot create tableview which would have been easy and will rectify the cGRects of label and textfields later.
int i = 0;
for(NSDictionary *myJsonDictionary in myJsonArray)
{
//UILabel *label = (UILabel *)[arrayLabel objectAtIndex:i++];
//[label setText:myJsonDictionary[#"Name"]];
NSUserDefaults *defaultNames = [NSUserDefaults standardUserDefaults];
NSString *name = myJsonDictionary[#"Name"];
[defaultNames setObject:name forKey:#"QUESTIONNAME"];
NSLog(#"Value is %# \n", name);
i++;
}
NSLog(#"Number of cycles in for-each = %d", i);
[self putLabelsInScrollView:i];
- (void) putLabelsInScrollView:(int)numberOfLables
{
for(int i = 0 ; i < numberOfLables ; i++)
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, yPosition_label, 261, 30)];
[label setFont:[UIFont fontWithName:#"Helvetica Neue" size:12.0f]];
label.numberOfLines = 2;
NSUserDefaults *defaultNameFetch = [NSUserDefaults standardUserDefaults];
NSString *fetchedString = [defaultNameFetch objectForKey:#"QUESTIONNAME"];
[label setText:[NSString stringWithFormat:#"%#", fetchedString]];
//[label setText:myJsonDictionary[#"Name"]];
[self.scroll addSubview:label];
yPosition_label += 80;
UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(10, yPosition_text, 261, 30)];
text.borderStyle = UITextBorderStyleRoundedRect;
text.textColor = [UIColor blackColor];
text.font = [UIFont systemFontOfSize:12.0];
text.backgroundColor = [UIColor clearColor];
text.keyboardType = UIKeyboardTypeDefault;
text.delegate = self;
[self.scroll addSubview:text];
yPosition_text += 100;
yPosition_result = yPosition_label + yPosition_text;
}
[self.scroll setContentSize:CGSizeMake(self.scroll.frame.size.width, yPosition_result)];
[self.view addSubview:self.scroll];
}
Just Try this...
for(NSDictionary *myJsonDictionary in myJsonArray)
{
NSString *name = myJsonDictionary[#"Name"];
[self putLabelsInScrollView:name];
NSLog(#"Value is %# \n", name);
}
[self.scroll setContentSize:CGSizeMake(self.scroll.frame.size.width, yPosition_result)];
[self.view addSubview:self.scroll];
- (void) putLabelsInScrollView:(NSString *)labelText
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, yPosition_label, 261, 30)];
[label setFont:[UIFont fontWithName:#"Helvetica Neue" size:12.0f]];
label.numberOfLines = 2;
[label setText:labelText];
//[label setText:myJsonDictionary[#"Name"]];
[self.scroll addSubview:label];
yPosition_label += 80;
UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(10, yPosition_text, 261, 30)];
text.borderStyle = UITextBorderStyleRoundedRect;
text.textColor = [UIColor blackColor];
text.font = [UIFont systemFontOfSize:12.0];
text.backgroundColor = [UIColor clearColor];
text.keyboardType = UIKeyboardTypeDefault;
text.delegate = self;
[self.scroll addSubview:text];
yPosition_text += 100;
yPosition_result = yPosition_label + yPosition_text;
}
Replace your code with this:
Fetching results:
int i = 0;
NSMutableArray *texts = [NSMutableArray array];
for(NSDictionary *myJsonDictionary in myJsonArray)
{
//UILabel *label = (UILabel *)[arrayLabel objectAtIndex:i++];
//[label setText:myJsonDictionary[#"Name"]];
NSUserDefaults *defaultNames = [NSUserDefaults standardUserDefaults];
NSString *name = myJsonDictionary[#"Name"];
[texts addObject:name];
NSLog(#"Value is %# \n", name);
i++;
}
NSLog(#"Number of cycles in for-each = %d", i);
[self putLabelsInScrollView:i withTexts:texts];
And method for putting labels' texts
- (void) putLabelsInScrollView:(int)numberOfLables withTexts:(NSArray *)texts
{
for(int i = 0 ; i < numberOfLables ; i++)
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, yPosition_label, 261, 30)];
[label setFont:[UIFont fontWithName:#"Helvetica Neue" size:12.0f]];
label.numberOfLines = 2;
NSUserDefaults *defaultNameFetch = [NSUserDefaults standardUserDefaults];
NSString *fetchedString = texts[i];
[label setText:fetchedString];
//[label setText:myJsonDictionary[#"Name"]];
[self.scroll addSubview:label];
yPosition_label += 80;
UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(10, yPosition_text, 261, 30)];
text.borderStyle = UITextBorderStyleRoundedRect;
text.textColor = [UIColor blackColor];
text.font = [UIFont systemFontOfSize:12.0];
text.backgroundColor = [UIColor clearColor];
text.keyboardType = UIKeyboardTypeDefault;
text.delegate = self;
[self.scroll addSubview:text];
yPosition_text += 100;
yPosition_result = yPosition_label + yPosition_text;
}
[self.scroll setContentSize:CGSizeMake(self.scroll.frame.size.width, yPosition_result)];
[self.view addSubview:self.scroll];
}
I have a UIScrollView with a list of UIViews within it. Bit like a fancy tableview. One issue I am having is the buttons work ok for the first 3 'rows' in the scrollview, but none of the buttons after this respond when i scroll down. Looks like its working ok for the buttons that show on screen when the view has loaded but anything further down when i scroll will now respond at all...
code from within the uiview repeated within uiscrollview
-(void)addButtons
{
UIButton *visiteWebSite = [UIButton buttonWithType:UIButtonTypeCustom];
[visiteWebSite addTarget:self
action:#selector(visitSite:)
forControlEvents:UIControlEventTouchDown];
[visiteWebSite setTintColor:[UIColor colorWithRed:247 green:143 blue:30 alpha:1.0]];
visiteWebSite.frame = CGRectMake(440.0, 10.0, 120.0, 26.0);
if(![self IsPhone5]) {
visiteWebSite.frame = CGRectMake(350.0, 10.0, 120.0, 26.0);
}
//visiteWebSite.backgroundColor = [UIColor orangeColor]; //[UIColor colorWithRed:247 green:143 blue:30 alpha:1.0];
[visiteWebSite setBackgroundImage:[UIImage imageNamed:#"orangeBG"] forState:UIControlStateNormal];
[visiteWebSite setTitle:#"VISITE WEBSITE" forState:UIControlStateNormal];
visiteWebSite.titleLabel.font = [UIFont fontWithName:#"arial" size:12];
[self addSubview:visiteWebSite];
UIButton *getDirections = [UIButton buttonWithType:UIButtonTypeCustom];
[getDirections addTarget:self
action:#selector(getDirections:)
forControlEvents:UIControlEventTouchDown];
[getDirections setTitle:#"GET DIRECTIONS" forState:UIControlStateNormal];
getDirections.titleLabel.font = [UIFont fontWithName:#"arial" size:12];
getDirections.frame = CGRectMake(440.0, 46.0, 120.0, 26.0);
if(![self IsPhone5]) {
getDirections.frame = CGRectMake(350.0, 46.0, 120.0, 26.0);
}
[getDirections setBackgroundImage:[UIImage imageNamed:#"orangeBG"] forState:UIControlStateNormal];
[self addSubview:getDirections];
}
Code from Parent View containing the UIScrollView
-(void)performSearch
{
[self.loadinglabel removeFromSuperview];
NSString* searchTerm = txtSearch.text;
searchTerm = [searchTerm stringByReplacingOccurrencesOfString:#" " withString:#""];
NSData *urldata = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.collectioncosmetics.co.uk/storelocatorapi?store=%#",searchTerm]]];
NSString *json = [[NSString alloc] initWithData:urldata encoding:NSUTF8StringEncoding];
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSArray *jsonObjects = [jsonParser objectWithString:json];
float y = 0;
float height = 84;
if([jsonObjects count] < 1) {
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:#"NO RESULTS" message:#"There are no stores near the postcode you searched" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alertView show];
[self back:nil];
return;
}
for (int i = 0; i < [jsonObjects count]; i++)
{
NSDictionary *dict = [jsonObjects objectAtIndex:i];
CARStoreResult* result = [[CARStoreResult alloc] initWithFrame:CGRectMake(0, height*i, tv.frame.size.width, height)];
result.name = [dict objectForKey:#"name"];
result.street = [dict objectForKey:#"street"];
result.area = [dict objectForKey:#"area"];
result.county = [dict objectForKey:#"County"];
result.postcode = [dict objectForKey:#"PostCode"];
result.distance = [dict objectForKey:#"distance"];
result.usersPostCode = searchTerm;
result.y = y;
result.num = i;
y = y + height;
[result build];
[tv addSubview:result];
}
[tv setFrame:CGRectMake(tv.frame.origin.x, tv.frame.origin.y, tv.frame.size.width, height*[jsonObjects count])];
[self.scrollView setContentSize:tv.frame.size];
[Flurry logEvent:#"Store Locator"];
}
FIXED!
instead of adding the views to a view within the scrollview i added them just directly to the scrollview. with the scrollview having scrollView.canCancelContentTouches set to NO.
//[tv addSubview:result];
[self.scrollView addSubview:result];
}
//[tv setFrame:CGRectMake(tv.frame.origin.x, tv.frame.origin.y, tv.frame.size.width, height*[jsonObjects count])];
[self.scrollView setContentSize:CGSizeMake(320, height*[jsonObjects count])];
//[self.scrollView setContentSize:tv.frame.size];
[Flurry logEvent:#"Store Locator"];
What I am trying to do is align views in a grid that are in an array. I have created the views and the array.
for (int i = 0; i < [directoryContents count]; i++){
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,120)];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, 100, 100);
button.accessibilityIdentifier = [directoryContents objectAtIndex:i];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 100, 20)];
label.textAlignment = NSTextAlignmentCenter;
label.text = [directoryContents objectAtIndex:i];
[containerView addSubview:button];
[containerView addSubview:label];
[self.view addSubview:containerView];
[_containerViewArray addObject:containerView];
}
[self layoutViews:_containerViewArray inView:self.view];
What I have working is aligning them next to each other the problem I am having is I need to have them wrap down instead of going off the edge. What I am doing to algin them is this
- (void)layoutViews:(NSArray *)views inView:(UIView *)contentView
{
NSInteger overallWidth = 0;
for ( UIView *view in views ) {
overallWidth += view.frame.size.width;
}
CGSize contentSize = contentView.frame.size;
CGFloat startOffset = (contentSize.height - overallWidth)/2.0;
CGFloat offset = startOffset;
for ( UIView *view in views ) {
CGRect frame = view.frame;
frame.origin.x = offset;
view.frame = frame;
offset += view.frame.size.width;
}
}
If we assumed that we have an array of sections (your views) and you need to layout 3 item per row the view has size 98*98 and spacing 6.5px horizontally and 8px Vertically
for (int i = 0; i< [sectionsArray count]; i++) {
int row = (int)i/3;
int col = i%3;
float x = 6.5 + (104.5*col);
float y = 8 + (106*row);
UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(x, y, 98, 98)];
sectionView.backgroundColor = [UIColor clearColor];
//button
UIButton *sectionButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[sectionButton setTintColor:[UIColor grayColor]];
sectionButton.frame = CGRectMake(0, 0, 98, 98);
sectionButton.tag = i+100;
[sectionButton addTarget:self action:#selector(showSectionDetail:) forControlEvents:UIControlEventTouchUpInside];
[sectionView addSubview:sectionButton];
//adding title
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 75, 98, 20)];
titleLabel.textAlignment = UITextAlignmentCenter;
titleLabel.backgroundColor=[UIColor clearColor];
titleLabel.font=[UIFont fontWithName:#"Helvetica" size:14];
titleLabel.textColor = [UIColor colorWithRed:241.0/255.0 green:124.0/255.0 blue:22.0/255.0 alpha:1.0];
titleLabel.text = [[sectionsArray objectAtIndex:i] objectForKey:#"Title"];
[sectionView addSubview:titleLabel];
[titleLabel release];
[scroll addSubview:sectionView];
[sectionView release];
}
int numberOfRows;
if ([sectionsArray count]/3.0f == 0) {
numberOfRows = [sectionsArray count]/3;
}else{
numberOfRows = [sectionsArray count]/3 +1;
}
scroll setContentSize:CGSizeMake(320, numberOfRows*106);
Here's what I used until the UICollectionView was released, easy to modify to accommodate for how many rows you want in the grid, and the size of the views.
NSUInteger buttonWidth = 100;
NSUInteger buttonHeight = 100;
NSUInteger space = 5;
float scrollContentY = (ceilf((float)imageNames.count / 3.0f) * (buttonHeight + space));
[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
int row = idx / 3;
int column = idx % 3;
UIView *view = [UIView new];
[view setBackgroundColor:[UIColor redColor]];
view.frame = CGRectMake((buttonWidth + space) * column + space, (buttonHeight + space) * row + space , buttonWidth, buttonHeight);
[view setTag:(NSInteger)idx];
[self.scrollView addSubview:view];
[self.scrollView setContentSize:CGSizeMake(self.scrollView.frame.size.width, scrollContentY)];
}];
Mind you, this might not be advisable if you have a large array to enumerate because this doesn't have any kind of reusable views. It will alloc/init a view for every item in the array.
i am fetching a list of photos from a server and displaying them. i'm using GCD to thread the server calls. I got it working, but i want to add in a UIActivityIndicator for each UIImageView to show that its doing something and will appear.
i'm not sure what the best method would be.
code:
UIScrollView *myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, photoView.frame.size.height)];
myScrollView.backgroundColor = [UIColor whiteColor];
myScrollView.pagingEnabled = TRUE;
myScrollView.scrollEnabled = TRUE;
myScrollView.frame = CGRectMake(myScrollView.frame.origin.x, myScrollView.frame.origin.y, (6 * THUMBNAIL_SIZE) + (PHOTO_VIEWER_OFFSET_COLUM_1 * 2), myScrollView.frame.size.height);
//get list of photos
for (int i = 0; i < 6; i++)
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSLog(#"async thread %#", [NSThread currentThread]);
//retrieveThumbnailedGeotaggedPhotoWithPhotoID will make a server call
MyUIImageView *myImageView = [[MyUIImageView alloc] initWithImage:[self retrieveThumbnailedGeoTaggedPhotoWithPhotoID:#"test"]];
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"main thread %#", [NSThread currentThread]);
myImageView.frame = CGRectMake(myImageView.frame.origin.x, myImageView.frame.origin.y, THUMBNAIL_SIZE, THUMBNAIL_SIZE);
myImageView.backgroundColor = [UIColor clearColor];
myImageView.position = i;
myImageView.isEnlarged = FALSE;
myImageView.delegate = self;
int group = (i / 6);
myImageView.frame = CGRectMake((i * myImageView.frame.size.width) + (PHOTO_VIEWER_OFFSET_COLUM_1 * ((group * 2) + 1)),
PHOTO_VIEWER_OFFSET_COLUM_1,
myImageView.frame.size.width,
myImageView.frame.size.height);
myScrollView.contentSize = CGSizeMake((myScrollView.frame.size.width * (group + 1)), myScrollView.contentSize.height);
[myScrollView addSubview:myImageView];
});
});
}
i'm pretty sure animating and stopping the activityIndicator needs to be on the main thread, but not sure how to include it. it needs to be animating during the "retrieveThumbnailedGeoTaggedPhotoWithPhotoID" method which is in a thread (but not main thread).
k, i re-ordered it:
for (int i = 0; i < 8; i++)
{
//create the subviews first
MyUIImageView *myImageView = [[MyUIImageView alloc] initWithFrame:CGRectMake((i * THUMBNAIL_SIZE) + (PHOTO_VIEWER_OFFSET_COLUM_1 * (((i / 6) * 2) + 1)),
PHOTO_VIEWER_OFFSET_COLUM_1,
THUMBNAIL_SIZE,
THUMBNAIL_SIZE)];
myImageView.backgroundColor = [UIColor whiteColor];
[myScrollView addSubview:myImageView];
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinner.center = CGPointMake(THUMBNAIL_SIZE / 2, THUMBNAIL_SIZE / 2);
[myImageView addSubview:spinner];
[spinner startAnimating];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
UIImage *myImage = [[UIImage alloc] init];
//only make the server call in the async queue
myImage = [self retrieveThumbnailedGeoTaggedPhotoWithPhotoID:#"test"];
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"main thread %#", [NSThread currentThread]);
//MyUIImageView *myImageView = [[MyUIImageView alloc] initWithImage:myImage];
[myImageView setImage:myImage];
myImageView.frame = CGRectMake(myImageView.frame.origin.x, myImageView.frame.origin.y, THUMBNAIL_SIZE, THUMBNAIL_SIZE);
myImageView.backgroundColor = [UIColor clearColor];
myImageView.position = i;
myImageView.isEnlarged = FALSE;
myImageView.delegate = self;
int group = (i / 6);
myImageView.frame = CGRectMake((i * myImageView.frame.size.width) + (PHOTO_VIEWER_OFFSET_COLUM_1 * ((group * 2) + 1)),
PHOTO_VIEWER_OFFSET_COLUM_1,
myImageView.frame.size.width,
myImageView.frame.size.height);
myScrollView.contentSize = CGSizeMake((myScrollView.frame.size.width * (group + 1)), myScrollView.contentSize.height);
[spinner stopAnimating];
});
});
}