UIButtons in UIScrollView stop working after 3 rows - objective-c

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"];

Related

remove objects from array based on the index

I have array of images here i am doing check and uncheck the images finally i have delete button which are the images i check i need to remove the images from array based on the button selection
here is my code
- (IBAction)delete_btn_touch:(id)sender {
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
for(int i=0; i<_GalleryimageArry.count;i++){
_imageV = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.view.frame) * i/2*0.6, 0, 100, 100)];
self.Crossbtn =[[UIButton alloc]initWithFrame:CGRectMake(_imageV.image.size.width/2+80,0,20,20)];
UIImage *btnImage = [UIImage imageNamed:#"unselectimag"];
[self.Crossbtn setImage:btnImage forState:UIControlStateNormal];
_imageV.contentMode = UIViewContentModeScaleAspectFill;
_imageV.image = [_GalleryimageArry objectAtIndex:i];
[_imageV setUserInteractionEnabled:YES];
_imageV.tag = i;
self.Crossbtn.tag =i;
[self.Crossbtn addTarget:self action:#selector(deleteImage:) forControlEvents:UIControlEventTouchUpInside];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(imageTapMethod:)];
[_imageV addGestureRecognizer:tap];
[self.imageV addSubview:self.Crossbtn];
[self.imageGalleryscroll addSubview:_imageV];
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}
self.imageGalleryscroll.delegate = self;
index=0;
self.imageGalleryscroll.contentSize = CGSizeMake(CGRectGetWidth(self.view.frame) * _GalleryimageArry.count/2*0.7, CGRectGetHeight(self.imageGalleryscroll.frame));
[self.imageGalleryscroll setPagingEnabled:YES];
[self.imageGalleryscroll setShowsHorizontalScrollIndicator:NO];
self.imageGalleryscroll.alwaysBounceVertical = NO;
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
-(void)deleteImage:(UIButton *)sender{
btn = (UIButton *)sender;
self.add_delete_view.hidden =YES;
self.deleteview.hidden=NO;
if( [[btn imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:#"unselectimag"]])
{
[btn setImage:[UIImage imageNamed:#"Crossimg"] forState:UIControlStateNormal];
[btn setSelected:YES];
[btn setTag:index];
}
else
{
[btn setImage:[UIImage imageNamed:#"unselectimag"] forState:UIControlStateNormal];
// other statements
self.selectedimages =#"No";
image = [self.GalleryimageArry objectAtIndex:index];
[self.GalleryimageArry addObject:image];
}
NSLog(#"%#", self.GalleryimageArry);
}
- (IBAction)delete_all_img_btn_touch:(id)sender {
// self.view (change it with your button superview)
if (btn.selected) {
[self.GalleryimageArry removeObjectAtIndex:index];
}
//here i need to removeObjectAtIndex:index based on the how many button are selected
}
any one help me to solve this issues
thanks in advance
Use the following code, where you want to clear the back stack of controllers.
-(void)clearStack
{
NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];
[navigationArray removeAllObjects];
//[navigationArray removeObjectAtIndex: 2];
self.navigationController.viewControllers = navigationArray;
}

How to show one by one alert at different Time and delay

i have to show different type of alerts with different time delay, Display the alerts one by one.one alert show and stay some time then next alert show with delay ....one by one showing This is my code
for ( int j = 0; j < [[CMAppData appData].arrayDistanceAlert count]; j++)
{
CMBeaconsDisplayList * displayData = [[CMAppData appData].arrayDistanceAlert objectAtIndex:j];
if ([displayData.type isEqualToString:#"1"])
{
if ([displayData.type isEqualToString:#"1"] &&[displayData.displayForTime isEqualToString:#"0"]) {
[self performSelector:#selector(dismissAlertView:) withObject:displayData afterDelay:[displayData.displayForTime intValue]*60];
}
else{
double delayInSeconds =[displayData.displayForTime intValue] *10 ;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
NSLog(#"%f",delayInSeconds);
UIAlertView * alert =[[UIAlertView alloc] initWithTitle:displayData.title message:displayData.content delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"pause", nil];
alert.alertViewStyle =UIAlertViewStyleDefault;
[alert show];
[self performSelector:#selector(dismissUIAlertViewType:) withObject:alert afterDelay:15];
});
}
}
else {
if ([displayData.type isEqualToString:#"2"]&&[displayData.displayForTime isEqualToString:#"0"]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:displayData.title message:displayData.content delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
[alertView show];
}
else{
double delayInSeconds =[displayData.displayForTime intValue]*10;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, [UIScreen mainScreen].bounds.size.width-20, [UIScreen mainScreen].bounds.size.height-100)];
customView.backgroundColor = [UIColor blueColor];
[alertView setContainerView:customView];
UIScrollView *MyScrollVw= [[UIScrollView alloc]initWithFrame:CGRectMake(0 ,0 ,[UIScreen mainScreen].bounds.size.width-20 ,[UIScreen mainScreen].bounds.size.height-100)];
MyScrollVw.delegate= self;
[MyScrollVw setShowsHorizontalScrollIndicator:NO];
[MyScrollVw setShowsVerticalScrollIndicator:YES];
MyScrollVw.scrollEnabled= YES;
MyScrollVw.userInteractionEnabled= YES;
MyScrollVw.contentSize= CGSizeMake([UIScreen mainScreen].bounds.size.width-20 ,1150);//(width,height)
[customView addSubview:MyScrollVw];
UILabel * lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, customView.frame.size.width, 30.0)];
lblTitle.text = displayData.title;
lblTitle.font = [UIFont fontWithName:#"Arial" size:15.0];
lblTitle.numberOfLines = 1;
lblTitle.baselineAdjustment = UIBaselineAdjustmentAlignBaselines; // or UIBaselineAdjustmentAlignCenters, or UIBaselineAdjustmentNone
lblTitle.adjustsFontSizeToFitWidth = YES;
lblTitle.minimumScaleFactor = 10.0f/12.0f;
lblTitle.clipsToBounds = YES;
lblTitle.backgroundColor = [UIColor clearColor];
lblTitle.textColor = [UIColor whiteColor];
lblTitle.textAlignment = NSTextAlignmentCenter;
[MyScrollVw addSubview:lblTitle];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, lblTitle.frame.origin.y+lblTitle.frame.size.height, customView.frame.size.width, 250)];
displayData.image = [displayData.image stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
if(displayData.image && ![displayData.image isKindOfClass:[NSNull class]])
{
[imageView sd_setImageWithURL:[NSURL URLWithString:displayData.image] placeholderImage:nil options:/* DISABLES CODE */ (0) == 0 ? SDWebImageRefreshCached : 0];
}
if ([displayData.image length]==0)
{
[imageView setImage:[UIImage imageNamed:#""]];
}
[MyScrollVw addSubview:imageView];
NSString *videoString = displayData.video;
NSString *lastWord = [[videoString componentsSeparatedByString:#"="] lastObject];
self.playerView = [[YTPlayerView alloc]init];
self.playerView.frame = CGRectMake(0.0, imageView.frame.origin.y+imageView.frame.size.height, customView.frame.size.width, 250.0);
[self.playerView loadWithVideoId:lastWord playerVars:#{#"playsinline":#1}];
[MyScrollVw addSubview:self.playerView];
UIButton * btnPlayAudio = [[UIButton alloc] initWithFrame:CGRectMake(10.0,self.playerView .frame.origin.y+self.playerView .frame.size.height, customView.frame.size.width-20, 30)];
[ btnPlayAudio addTarget:self action:#selector(playAudio:) forControlEvents:UIControlEventTouchUpInside];
btnPlayAudio.backgroundColor = [UIColor redColor];
[btnPlayAudio setTitle:#"Play Audio" forState:UIControlStateNormal];
[btnPlayAudio setAccessibilityValue:displayData.audio];
[MyScrollVw addSubview:btnPlayAudio];
UILabel * lblDescription = [[UILabel alloc] initWithFrame:CGRectMake(10.0,btnPlayAudio .frame.origin.y + btnPlayAudio .frame.size.height, customView.frame.size.width-20, 100)];
lblDescription.text = displayData.content;
lblDescription.font = [UIFont fontWithName:#"Arial" size:15.0];
lblDescription.numberOfLines = 0;
[lblDescription sizeToFit];
lblDescription.baselineAdjustment = UIBaselineAdjustmentAlignBaselines; // or UIBaselineAdjustmentAlignCenters, or UIBaselineAdjustmentNone
lblDescription.adjustsFontSizeToFitWidth = YES;
lblDescription.minimumScaleFactor = 10.0f/12.0f;
lblDescription.clipsToBounds = YES;
lblDescription.backgroundColor = [UIColor clearColor];
lblDescription.textColor = [UIColor whiteColor];
lblDescription.textAlignment = NSTextAlignmentCenter;
[MyScrollVw addSubview:lblDescription];
[alertView show];
[self performSelector:#selector(dismissImageAlertView:) withObject:alertView afterDelay:15];
});
delayInSeconds = delayInSeconds * 10;
}
}
}
setTimeout: allows to run a function once after the interval of time.
alert('Before the Delay');
function afterDelay() {
alert('After the Delay');
}
setTimeout(afterDelay, 2000);

UIImageView transparent black on a cell bug (Objective-C)

I have a UIImageView installed on my cell, it is transparent black, but when I scroll the CollectionView and I raise my UIImageView but there is always more to transprence.
See picture :
1 - I is not even scroll
2 - After a scroll
My code :
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"pictureCell";
MSContestListCollectionViewCell *cell = (MSContestListCollectionViewCell *)[self.collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
cell.titleContest.adjustsFontSizeToFitWidth = YES;
cell.titleContest.minimumScaleFactor = 0.5;
cell.pictureImageView.layer.cornerRadius = 5;
cell.pictureImageView.clipsToBounds = YES;
cell.titleView.layer.cornerRadius = 5;
cell.titleView.clipsToBounds = YES;
switch (_segmentedControl.selectedSegmentIndex) {
case 0: {
NSDictionary *searchResult = [self.readArray objectAtIndex:indexPath.item];
NSString *stringImage = [searchResult objectForKey:#"featuredImage"];
NSString *image = [NSString stringWithFormat:#"https://srv.mediaswapp.com/%#", stringImage];
[cell.pictureImageView sd_setImageWithURL:[NSURL URLWithString:image]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
cell.statusContest.text = [searchResult objectForKey:#"status"];
if ([[searchResult objectForKey:#"status"] isEqualToString:#"PAUSE"]) {
cell.titleContest.text = [NSString stringWithFormat:#"Concours en pause"];
/*
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(cell.contentView.frame.origin.x, cell.contentView.frame.origin.y, cell.contentView.frame.size.width, cell.contentView.frame.size.height)];
view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8f];
view.layer.cornerRadius = 5;
view.clipsToBounds = YES;
[cell.contentView addSubview:view];
*/
UIImageView *imagecellPause = [[UIImageView alloc] initWithFrame:CGRectMake(cell.contentView.frame.origin.x, cell.contentView.frame.origin.y, cell.contentView.frame.size.width, cell.contentView.frame.size.height)];
UIImage *cellImage = [UIImage imageNamed:#"cell-pause.png"];
imagecellPause.image = cellImage;
[cell.contentView addSubview:imagecellPause];
UIImageView *imagePause = [[UIImageView alloc] initWithFrame:CGRectMake(69.5, 69.5, 25, 25)];
UIImage *image = [UIImage imageNamed:#"Pause Filled-50 (1).png"];
imagePause.image = image;
[cell.contentView addSubview:imagePause];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 90, 150, 50)];
label.textColor = [UIColor whiteColor];
label.font = [UIFont fontWithName:#"Avenir-Book" size:12];
label.text = [searchResult objectForKey:#"description"];
label.adjustsFontSizeToFitWidth = YES;
label.minimumScaleFactor = 0.5;
[cell.contentView addSubview:label];
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(10, 105, 150, 50)];
label2.textColor = [UIColor whiteColor];
label2.font = [UIFont fontWithName:#"Avenir-Black" size:15];
label2.text = #"Concours en pause";
[cell.contentView addSubview:label2];
cell.titleView.hidden = YES;
} else {
cell.titleContest.text = [searchResult objectForKey:#"description"];
}
break;
}
case 1: {
NSDictionary *searchResult2 = [self.readArrayWinner objectAtIndex:indexPath.item];
NSString *stringImage = [searchResult2 objectForKey:#"featuredImage"];
NSString *image = [NSString stringWithFormat:#"https://srv.mediaswapp.com/%#", stringImage];
[cell.pictureImageView sd_setImageWithURL:[NSURL URLWithString:image]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
cell.titleContest.text = [searchResult2 objectForKey:#"description"];
cell.statusContest.text = [searchResult2 objectForKey:#"status"];
NSLog(#"le gagnant : %#", [searchResult2 valueForKeyPath:#"winners.name"]);
break;
}
case 2: {
NSDictionary *searchResult3 = [self.readArrayPhotos objectAtIndex:indexPath.item];
NSString *stringImage = [searchResult3 objectForKey:#"featuredImage"];
NSString *image = [NSString stringWithFormat:#"https://srv.mediaswapp.com/%#", stringImage];
[cell.pictureImageView sd_setImageWithURL:[NSURL URLWithString:image]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
cell.titleContest.text = [searchResult3 objectForKey:#"description"];
cell.statusContest.text = [searchResult3 objectForKey:#"status"];
break;
}
default:
break;
}
[_activity stopAnimating];
_label1.hidden = YES;
return cell;
}
Your CellForRowAtIndexPath should never contain addSubView, since everytime the cell is reloaded it will add the view. Thats why it keeps getting darker, it just adds view onto view.
Instead you should subclass your UICollectionViewCell and add the view in the subclass.

check answer and remove UIButton (Objective-C)

I have a series of questions and answers that it's loads randomly,each question have 3 choice, in one of my question I have just true and false,
my questions is how can I set my if statement, That if my answer is true or false don't show the last buttons,
Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSString *qOne = #"Question 1";
NSString *qTwo = #"Question 2";
NSString *qThree = #"Question 3";
NSString *qFour = #"Question 4";
NSString *answerOne = #"Après le souper";
NSString *answerTwo = #"1";
NSString *answerThree = #" Holstein";
NSString *answerFour = #" yes";
NSString *answer2One = #"Après un exercice physique";
NSString *answer2Two = #" 2";
NSString *answer2Three = #" Jersey";
NSString *answer2Four = #" No";
NSString *answer3One = #"Avant un exercice physique";
NSString *answer3Two = #" 4";
NSString *answer3Three = #" Canadienne";
I want to remove this part
NSString *answer3Four = #" ";
NSString *correctOne = #"Après un exercice physique";
NSString *correctTwo = #" 4";
NSString *correctThree = #" Yes";
NSString *correctFour = #" 14";
answerComments = [[NSArray alloc] initWithObjects: answerOne, answerTwo, answerThree, answerFour, nil];
answer2Comments = [[NSArray alloc] initWithObjects: answer2One, answer2Two, answer2Three, answer2Four, nil];
answer3Comments = [[NSArray alloc] initWithObjects: answer3One, answer3Two, answer3Three, answer3Four,nil];
qComments = [[NSArray alloc] initWithObjects:qOne, qTwo, qThree, qFour, nil];
correctComments = [[NSArray alloc] initWithObjects: correctOne, correctTwo, correctThree, correctFour, nil];
// A random string is selected and assigned to artist.
int rand = arc4random()%4;
NSString *artist = [qComments objectAtIndex:rand];
firstAnswer = [answerComments objectAtIndex:rand];
secondAnswer = [answer2Comments objectAtIndex:rand];
threeAnswer = [answer3Comments objectAtIndex:rand];
correct = [correctComments objectAtIndex:rand];
NSLog (#"%#",correct);
// Here's the problematic code:
[question setText:(artist)];
[question setFont:[UIFont fontWithName:#"HelveticaRoundedLTStd-Bd" size:42]];
question.adjustsFontSizeToFitWidth = NO;
question.numberOfLines = 0;
[test setTitle:(firstAnswer) forState:UIControlStateNormal];
[test setBackgroundImage:[UIImage imageNamed:#"activeBtn.png"] forState:UIControlStateHighlighted];
[ansONE setTitle:(secondAnswer) forState:UIControlStateNormal];
[ansONE setBackgroundImage:[UIImage imageNamed:#"activeBtn.png"] forState:UIControlStateHighlighted];
ansTWO = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[ansTWO addTarget:self
action:#selector(ansTWO:)
forControlEvents:UIControlEventTouchDown];
[ansTWO setTitle:(threeAnswer) forState:UIControlStateNormal];
[ansTWO setBackgroundImage:[UIImage imageNamed:#"activeBtn.png"] forState:UIControlStateHighlighted];
ansTWO.titleLabel.font = [UIFont fontWithName:#"HelveticaRoundedLTStd-Bd" size:24];
[ansTWO setTitleColor:[UIColor colorWithRed:21/255.0 green:119/255.0 blue:183/255.0 alpha:.77] forState:UIControlStateNormal];
ansTWO.titleLabel.textAlignment = UITextAlignmentCenter;
[ansTWO setTag:2];
UIImage *buttonImage = [UIImage imageNamed:#"quizBtn.png"];
[ansTWO setBackgroundImage:buttonImage forState:UIControlStateNormal];
ansTWO.frame = CGRectMake(243, 586,549, 56);
[self.view addSubview:ansTWO];
}
Assuming that you know how to interpret the answer to be TRUE or FALSE you can have some if statement like this:
//1st Option
if(answer){
button.hidden = YES;
//hide or unhide other buttons
}
//2 Option
if(answer){
[button removeFromSuperView];
//add or remove other buttons
}

Activity Indicator while loading images inside UIScrollView

I have UIScrollView that contains images from the server.
I should put Activity Indicator while the image is currently loading.
UIScrollView contains dynamic number of images from the server.
May I know how can I add activity indicators on each page while the image is loading and remove once image is loaded.
Here's my code to retrieve images:
NSDictionary *items = [NSDictionary dictionaryWithObject:dictInfo forKey:#"images"];
imageList = [items objectForKey:#"images"];
NSArray *img = [imageList objectForKey:#"list"];
NSInteger imgCount = [img count];
buttonArray = [[NSMutableArray alloc] init];
for (int i=0; i<imgCount; i++) {
NSDictionary *imgDict = [img objectAtIndex:i];
// REQUEST FOR IMAGES
NSString *imgPath = [imgDict objectForKey:#"image_slot"];
NSString *imgURL = imgPath;
__block ASIHTTPRequest *requestImage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:imgURL]];
[requestImage setCompletionBlock:^{
imgView = [UIImage imageWithData:[requestImage responseData]];
if (imgURL.length) {
[pendingRequests removeObjectForKey:imgURL];
}
scrollView.userInteractionEnabled = YES;
scrollView.exclusiveTouch = YES;
scrollView.canCancelContentTouches = YES;
scrollView.delaysContentTouches = YES;
scrollView.bounces = NO;
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
SWTUIButton *imgBtn = [[SWTUIButton alloc] initWithFrame:frame];
imgBtn.url = [requestImage.userInfo objectForKey:#"rURL"];
[imgBtn setImage:imgView forState:UIControlStateNormal];
imgBtn.backgroundColor = [UIColor clearColor];
[imgBtn addTarget:self action:#selector(buttonpushed:) forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:imgBtn];
[buttonArray addObject:imgBtn];
[imgBtn release];
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * img.count, self.scrollView.frame.size.height);
}];
I highly suggest you use NINetworkImageView from https://github.com/jverkoey/nimbus project.
It's very light and useful.
It has a delegate method to let you know when an image is loaded.
What you basically need to do is:
1. create an NINetworkImageView for each page, just like you do with UIImageView, and call set
NINetworkImageView* networkImageView = [[[NINetworkImageView alloc] initWithImage:initialImage]
autorelease];
networkImageView.delegate = self;
networkImageView.contentMode = UIViewContentModeCenter;
[networkImageView setPathToNetworkImage:
#"http://farm3.static.flickr.com/2484/3929945380_deef6f4962_z.jpg"
forDisplaySize: CGSizeMake(kImageDimensions, kImageDimensions)];
https://github.com/jverkoey/nimbus/tree/master/examples/photos/NetworkPhotoAlbums
the add the indicator to the networkImageView as a subview.
implement the delegate as follows:
-(void)networkImageView:(NINetworkImageView *)imageView didLoadImage:(UIImage *)image {
[imageView removeAllSubviews];
}
the end result would be a much smaller code for doing the same thing.