How to prevent scrollViewDidScroll getting call when View loads? - iphone

I have UITableView and its delegates are set via xib as shown in below image.
I have put some LOAD MORE CODE in method so that when user scrolldown, it sends request to server and load more values.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
NSLog(#"Veer Suthar Scrolling the view");
CGPoint offset = scrollView.contentOffset;
CGRect bounds = scrollView.bounds;
CGSize size = scrollView.contentSize;
UIEdgeInsets inset = scrollView.contentInset;
float y = offset.y + bounds.size.height - inset.bottom;
float h = size.height;
float reload_distance = 15;
if(y > h + reload_distance)
{
//Call the Method to load More Data...
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
if ([appDelegate.reach isReachable])
{
if (onceCallTheLoadMore) {
onceCallTheLoadMore = NO;
int startCountValue = [vouchersArray count]+1;
int endCountValue = [vouchersArray count] + 10;
startCount = [[NSString alloc] initWithString:[NSString stringWithFormat:#"%d", startCountValue]];
endCount = [[NSString alloc] initWithString:[NSString stringWithFormat:#"%d", endCountValue]];
NSString *totalCount = [[NSUserDefaults standardUserDefaults] valueForKey: #"totalCountOfFeaturedVouchers"];
int totalCountValue = [totalCount intValue];
if (endCountValue > totalCountValue) {
////
onceCallTheLoadMore = YES;
}else{
[self featuredWebService];
}
//Veer, call here method for load more
}else{
}
}
}
}
Here this methods gets called when View Loads.
how can I prevent it from calling when view loads.
I tried
[self.tableview setDelegate:nil]; //Used in ViewWillAppear and again in ViewDidLoad its set to SELF.
But its not working fine.
ViewDidLoad COde is
- (void)viewDidLoad
{
[super viewDidLoad];
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
{
if( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )480 ) < DBL_EPSILON ){
[self.tableView setFrame:CGRectMake(0, 64,320, 390)];
}else{
NSLog(#"ViewDidAppear is laoded ");
[self.tableView setFrame:CGRectMake(0, 64,320, 455)];
}
}
}
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
{
[self.view setBackgroundColor:[UIColor clearColor]];
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:#"nev_top_right_title.png"] forBarMetrics:UIBarMetricsDefault];
UIButton *locationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *locationBtnImage = [UIImage imageNamed:#"map.png"] ;
//[backBtn setTitle:#"Back" forState:UIControlStateNormal];
[locationBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
// [backBtn setValue:[UIFont boldSystemFontOfSize:13.0] forKey:#"font"];
[locationBtn setBackgroundImage:locationBtnImage forState:UIControlStateNormal];
[locationBtn addTarget:baseViewController action:#selector(locationBtnPressed) forControlEvents:UIControlEventTouchUpInside];
locationBtn.frame = CGRectMake(0, 0, 41, 35);
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:locationBtn] ;
self.navigationItem.leftBarButtonItem = leftButton;
UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *searchBtnImage = [UIImage imageNamed:#"search.png"] ;
//[backBtn setTitle:#"Back" forState:UIControlStateNormal];
[searchBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
// [searchBtn setValue:[UIFont boldSystemFontOfSize:13.0] forKey:#"font"];
[searchBtn setBackgroundImage:searchBtnImage forState:UIControlStateNormal];
[searchBtn addTarget:baseViewController action:#selector(searchBtnPressed) forControlEvents:UIControlEventTouchUpInside];
searchBtn.frame = CGRectMake(0, 0, 39, 30);
UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithCustomView:searchBtn] ;
self.navigationItem.rightBarButtonItem = rightBtn;
UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0.0, 0.0, 320.0, 25.0)];
UIImageView *logo = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"title_logo_ipad.png"]];
[logo setFrame:CGRectMake(62.0, -6.0, 62.0, 33.0)];
[titleView addSubview:logo];
//[titleView addSubview:title];
self.navigationItem.titleView = logo;
[self.navigationController.navigationBar subviews];
[titleView release];
[leftButton release];
[rightBtn release];
// [title release];
[logo release];
[(UITableView *)[self view] setSeparatorColor:[UIColor clearColor]];
}
else {
[(UITableView *)[self view] setSeparatorStyle:UITableViewCellSeparatorStyleNone];
UIEdgeInsets inset = UIEdgeInsetsMake(44, 0, 0, 0);
self.tableView.contentInset = inset;
self.tableView.scrollIndicatorInsets = inset;
[self.view setBackgroundColor:[UIColor clearColor]];
}
onceCallTheLoadMore = YES;
int startCountValue = [vouchersArray count]+1;
int endCountValue = [vouchersArray count] + 10;
startCount = [[NSString alloc] initWithString:[NSString stringWithFormat:#"%d", startCountValue]];
endCount = [[NSString alloc] initWithString:[NSString stringWithFormat:#"%d", endCountValue]];
self.vouchersArray = [[NSMutableArray alloc] initWithCapacity:0];
self.parser = [[[TBXMLParser alloc] init] autorelease];
parser.delegate = self;
self.arrFeaturedVouchers = [[NSMutableArray alloc]initWithCapacity:0];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
if ([appDelegate.reach isReachable])
{
[self performSelector:#selector(featuredWebService) withObject:nil afterDelay:0.1];
}
}
ViewWIllAPpear Code
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.view setBackgroundColor:[UIColor clearColor]];
if(voucherType == kVoucherTypeFeatured)
{
UIButton *locationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *locationBtnImage = [UIImage imageNamed:#"b_icon.png"] ;
//[backBtn setTitle:#"Back" forState:UIControlStateNormal];
[locationBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
// [backBtn setValue:[UIFont boldSystemFontOfSize:13.0] forKey:#"font"];
[locationBtn setBackgroundImage:locationBtnImage forState:UIControlStateNormal];
// Edited by Sugam on 19 Dec 2012
[locationBtn addTarget:[[UIApplication sharedApplication] delegate] action:#selector(locationBtnPressed) forControlEvents:UIControlEventTouchUpInside];
locationBtn.frame = CGRectMake(0, 0, 41, 35);
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:locationBtn] ;
self.navigationItem.leftBarButtonItem = leftButton;
[leftButton release];
}
UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *searchBtnImage = [UIImage imageNamed:#"seach_top.png"] ;
//[backBtn setTitle:#"Back" forState:UIControlStateNormal];
[searchBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
// [searchBtn setValue:[UIFont boldSystemFontOfSize:13.0] forKey:#"font"];
[searchBtn setBackgroundImage:searchBtnImage forState:UIControlStateNormal];
// Edited by Sugam on 19 Dec 2012
[searchBtn addTarget:[[UIApplication sharedApplication] delegate] action:#selector(searchBtnPressed) forControlEvents:UIControlEventTouchUpInside];
searchBtn.frame = CGRectMake(0, 0, 39, 30);
UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithCustomView:searchBtn] ;
self.navigationItem.rightBarButtonItem = rightBtn;
UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0.0, 0.0, 320.0, 25.0)];
UIImageView *logo;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
logo = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"title_logo.png"]];
}
else
{
logo = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"title_logo_ipad.png"]];
}
[logo setFrame:CGRectMake(62.0, -6.0, 62.0, 33.0)];
[titleView addSubview:logo];
//[titleView addSubview:title];
self.navigationItem.titleView = logo;
[self.navigationController.navigationBar subviews];
[titleView release];
// [title release];
[logo release];
[rightBtn release];
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
[self.tabBarController showTabBar];
}
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
{
if( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )480 ) < DBL_EPSILON ){
[self.tableView setFrame:CGRectMake(0, 64,320, 390)];
}else{
NSLog(#"ViewDidAppear is laoded ");
[self.tableView setFrame:CGRectMake(0, 64,320, 455)];
}
}
}
dispatch_async(dispatch_get_main_queue(), ^{
/* Do somthing here with UIKit here */
_iconDownloader = [[ImageCache alloc] init];
_iconDownloader.delegate = self;
startCount = [[NSString alloc] initWithString:[NSString stringWithFormat:#"0"]];
endCount = [[NSString alloc] initWithString:[NSString stringWithFormat:#"10"]];
[Flurry logEvent:#"Featured Section Browse" timed:YES]; //How long the user has spent on the app
[self getLocation];
AppDelegate *app = (AppDelegate*) [[UIApplication sharedApplication]delegate];
self.arrFeaturedVouchers = (NSMutableArray*) [app.dbCommunicator getAllFeaturedVouchers];
if ([self.arrFeaturedVouchers count]>0)
{
[self.vouchersArray removeAllObjects];
for (int i = 0; i<[self.arrFeaturedVouchers count]; i++)
{
FeaturedVoucher *aFeaturedVoucher = [self.arrFeaturedVouchers objectAtIndex:i];
Voucher *aVoucher = [app.dbCommunicator getVoucherInfoForCampaignId:aFeaturedVoucher.featuredCampaignId];
if(aVoucher)
{
[self.vouchersArray addObject:aVoucher];
////
}
}
[self.arrFeaturedVouchers removeAllObjects];
[self.tableView reloadData];
}
});
}
Any suggestion
Thanks in Advance.

In your viewWillApear method, you have [self.tableView reloadData] - this is causing the scrollView to call its delegate scrollViewDidScroll

Related

How to Save only that image which is long pressed and selected by user

Currently it is saving all images but i want to save only the one which is long pressed not all images in one shot only the one user selects
- (void)viewDidLoad
{ self.view.backgroundColor = [UIColor blackColor];
UIScrollView *imageScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
imageScrollView.pagingEnabled = YES;
NSInteger numberOfViews = 61;
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i * self.view.frame.size.width;
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton addTarget:self action:#selector(dismissView:) forControlEvents:UIControlEventTouchUpInside];
myButton.frame = CGRectMake(xOrigin, 10, 60, 35);
//[myButton addGestureRecognizer:tap];
[myButton.layer setMasksToBounds:YES];
[myButton.layer setCornerRadius:10.0f];
myButton.layer.borderWidth = 2;
myButton.layer.borderColor = [[UIColor whiteColor] CGColor];
[myButton setTitle:#"Done" forState:UIControlStateNormal];
myButton.backgroundColor = [UIColor clearColor];
NSString *imageName = [NSString stringWithFormat:#"image%d.png", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
_imageView.tag = 128;
imageView.frame = CGRectMake(xOrigin, 0, self.view.frame.size.width, self.view.frame.size.height);
UILongPressGestureRecognizer *gestureRecognizer = [[UILongPressGestureRecognizer alloc]
initWithTarget:self
action:#selector(handleLongPress:)];
//imageScrollView.userInteractionEnabled = YES;
[imageScrollView addGestureRecognizer:gestureRecognizer];
gestureRecognizer.delegate = self;
[gestureRecognizer release];
[imageScrollView addSubview:imageView];
[imageScrollView addSubview:myButton];
//[imageView release];
}
imageScrollView.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews, self.view.frame.size.height);
[self.view addSubview:imageScrollView];
[imageScrollView release];
}
- (void)handleLongPress:(UILongPressGestureRecognizer*)gestureRecognizer{
if (gestureRecognizer.state == UIGestureRecognizerStateBegan){
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:#"Save Photo", nil];
actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
[actionSheet showInView:self.view];
[actionSheet release];
}
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
NSInteger numberOfViews = 61;
for (int i = 0; i < numberOfViews; i++) {
NSString *imageName = [NSString stringWithFormat:#"image%d.png", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
UIImageWriteToSavedPhotosAlbum(imageView.image, self, #selector(image: didFinishSavingWithError:contextInfo:), nil);
}
}
How to code for that
Thanks for help
In the handleLongPress: function, use this:
UIGestureRecognizer *gestureRecognizer;
CGPoint gesturePoint = [gestureRecognizer locationInView:self.view];
Then check all of your buttons using a for loop like you have there. Use this to check if it is the pressed image:
if(CGRectContainsPoint(myButton.frame,gesturePoint)){
//save the image stored in myButton
//break will exit the for loop early, so if the view comes early in the list,
//it doesn't have to check the rest.
break;
}

UITapGestureRecognizer and UIButton

UITapGestureRecognizer and UIButton are not working together.
UIButton alone is working fine without UITapGesturerecognizer. It shows in all scrolling image views but after adding UITapGestureReconizer feature it is not showing UIButton when tapped.
BOOL numberofTaps;
#interface ImageScrollViewController : UIViewController <UIGestureRecognizerDelegate>
#property (nonatomic, assign) UITapGestureRecognizer *recognizer;
- (void)handleTap:(UIGestureRecognizer*)sender;
//////////////////////////
- (void)viewDidLoad {
self.view.backgroundColor = [UIColor blackColor];
UIScrollView *imageScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
imageScrollView.pagingEnabled = YES;
NSInteger numberOfViews = 61;
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i * self.view.frame.size.width;
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton addTarget:self action:#selector(dismissView:) forControlEvents:UIControlEventTouchUpInside];
myButton.frame = CGRectMake(xOrigin, 10, 60, 35);
[myButton.layer setMasksToBounds:YES];
[myButton.layer setCornerRadius:10.0f];
myButton.layer.borderWidth = 2;
myButton.layer.borderColor = [[UIColor whiteColor] CGColor];
[myButton setTitle:#"Done" forState:UIControlStateNormal];
myButton.backgroundColor = [UIColor blackColor];
myButton.hidden = YES;
NSString *imageName = [NSString stringWithFormat:#"image%d.png", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(xOrigin, 0, self.view.frame.size.width, self.view.frame.size.height);
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTap:)];
recognizer.numberOfTapsRequired = 1;
[imageView addGestureRecognizer:recognizer];
imageView.userInteractionEnabled = YES;
recognizer.delegate = self;
numberofTaps = 1;
[recognizer release];
[imageScrollView addSubview:imageView];
[imageScrollView addSubview:myButton];
// [imageScrollView addGestureRecognizer:tap];
// [imageView addSubview:tap];
[imageView release];
}
imageScrollView.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews, self.view.frame.size.height);
[self.view addSubview:imageScrollView];
[imageScrollView release];
}
EDIT: Howcome this works but when i only uncomment myButton.hidden= NO then it works but still doesn't shows my button DONE on the imageviews
- (void)handleTap:(UIGestureRecognizer*)sender {
// if(numberofTaps == 1){
CGPoint tapPoint = [sender locationInView:_imageScrollView];
int tapX = (int) tapPoint.x;
int tapY = (int) tapPoint.y;
NSLog(#"TAPPED X:%d Y:%d", tapX, tapY);
//_myButton.hidden = NO;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Hello" message:#"How are you?" delegate:nil cancelButtonTitle:#"I'm awesome." otherButtonTitles:nil];
[alert show];
[alert release];
}
What is the reason that otherwise it is working but not showing Done UIButton.
First you have to find button which you have to show. So for that you will have to setTag: on your UIButton before adding them to scrollView
like this -
myButton.tag = i;
Then add tag to your UIImageView also before adding them to scrollView like this -
imageView.tag = i*100;
Now in handleTap: method you can compare tags and can get the button which you have to show.
-(void)handleTap:(UIGestureRecognizer *)sender
{
//getting all buttons of scrollView
for(UIButton *button in scrollView.subviews)
{
//comparing tags
if(button.tag == sender.view.tag/100)
{
button.hidden = NO;
}
}
}
Do this, remove your if Condition.

Background image not displayed on UIView

I have a class that implements "UIView" and inside - (void)drawRect:(CGRect)rect method I add some custom buttons to self. Inside a UIViewController I declare an instance of this view and i add it to self.view.
If i do this in - (void)viewDidLoad, everything works perfect, but if I create a method that is called when I push a button, and add that view to self.view, the buttons background is displayed after a few second. Till then only the name of the button appears written in white.
What do i do wrong?
Regards
#implementation CustomButton
#synthesize isPressed, buttonViewNumber;
- (id)initWithFrame:(CGRect)frame
title:(NSString *)title
tag:(int)tag
{
self = [super initWithFrame:frame];
if (self) {
[self setTitle:title forState:UIControlStateNormal];
[self setTag:tag];
self.titleLabel.font = [UIFont fontWithName:#"Helvetica" size:14];
self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
self.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
[self setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[self setBackgroundImage:[[UIImage imageNamed:#"btn_white_add.png"] stretchableImageWithLeftCapWidth:20.0 topCapHeight:0.0] forState:UIControlStateNormal];
[self addTarget:self action:#selector(didSelect) forControlEvents:UIControlEventTouchUpInside];
self.isPressed = NO;
}
return self;
}
#implementation ButtonsView
#synthesize listOfButtons;
- (id)initWithFrame:(CGRect)frame bundle:(NSArray *)data
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
listOfNames = [[NSArray arrayWithArray:data] retain];
listOfButtons = [[NSMutableArray alloc] init];
currentViewNumber = 0;
viewNumber = 0;
}
return self;
}
- (void)drawRect:(CGRect)rect
{
CGSize maximumLabelSize = CGSizeMake(300,24);
UIFont *buttonFont = [UIFont fontWithName:#"Helvetica" size:14.0];
float lineSize = 0;
float lineNumber = 0;
NSArray *listOfFrameX = [NSArray arrayWithObjects:
[NSString stringWithFormat:#"%d",FIRST_LINE_Y],
[NSString stringWithFormat:#"%d",SECOND_LINE_Y],
[NSString stringWithFormat:#"%d",THIRD_LINE_Y],
nil];
for (int i = 0; i < [listOfNames count]; i++) {
CGSize expectedLabelSize = [[[listOfNames objectAtIndex:i] objectForKey:#"name"] sizeWithFont:buttonFont
constrainedToSize:maximumLabelSize
lineBreakMode:UILineBreakModeTailTruncation];
if ((lineSize + expectedLabelSize.width) > 260) {
lineNumber++;
lineSize = 0;
}
if (lineNumber > 2) {
viewNumber ++;
lineSize = 0;
lineNumber = 0;
}
CGRect newFrame = CGRectMake(lineSize,
[[listOfFrameX objectAtIndex:lineNumber] floatValue],
expectedLabelSize.width+30,
24);
CustomButton *myButton = [[CustomButton alloc] initWithFrame:newFrame
title:[[listOfNames objectAtIndex:i] objectForKey:#"name"]
tag:[[[listOfNames objectAtIndex:i] objectForKey:#"id"] intValue]];
myButton.buttonViewNumber = viewNumber;
[listOfButtons addObject:myButton];
if (viewNumber == 0) {
[self addSubview:myButton];
}
lineSize += expectedLabelSize.width + 40;
[myButton release];
}
}
this way it works:
- (void)viewDidLoad
{
[super viewDidLoad];
placeholders = [[NSArray arrayWithObjects:
something,something, something,something,nil] retain];
CGRect frame = CGRectMake(10, 247, 300, 84);
buttonsView = [[ButtonsView alloc] initWithFrame:frame bundle:placeholders];
[self.view addSubview:buttonsView];
and like this is doesnt work:
- (void)getCompanyNames:(id)result
{
NSArray *listOfCompanies = (NSArray *)result;
CGRect frame = CGRectMake(10, 247, 300, 84);
buttonsView = [[ButtonsView alloc] initWithFrame:frame bundle:listOfCompanies];
[self.view addSubview:buttonsView];
}
i need to add the "buttonsView" object to self.view after the -viewDidLoad
drawRect: isn't exactly the place you should be creating subviews (Buttons are subviews) for your view. This should either go into initWithFrame: or awakeFromNib, depending on your view creation method: programmatically or using a nib.

UIButton failed to call functions?

I have a viewcontroller(mainViewController) and view class(UIView class, mainView). mainViewController, I called a method "generateView" from mainView class. Here is the code:
Method 1:
- (void) generateView {
container = [[UIScrollView alloc] initWithFrame: CGRectMake(10, 10, 500, 300)];
container.backgroundColor = [UIColor clearColor];
container.contentSize = CGSizeMake(500,1200);
container.showsVerticalScrollIndicator = YES;
[container setScrollEnabled:TRUE];
container.backgroundColor = [UIColor redColor];
int row = 0;
int col = 0;
for (int i = 0; i < 5; i++) {
if(i % 4 == 0 && i != 0){
row++;
col = 0;
}
UIButton *b = [[UIButton alloc] initWithFrame: CGRectMake(col*120, row*120, 100, 100)];
NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:[NSString stringWithFormat:#"%#/images/items/%i.png", HOSTADDR, i ]]];
[b setBackgroundImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal];
[b setBackgroundColor: [UIColor colorWithRed:0x42/255.0f green:0x30/255.0f blue:0x27/255.0f alpha:1]];
[b setTag: i];
[b addTarget:self action:#selector(testFunction:) forControlEvents:UIControlEventTouchUpInside];
[b setEnabled:TRUE];
[b setUserInteractionEnabled:TRUE];
[container addSubview:b];
col++;
}
[self addSubview:container];
}
- (void) testFunction: (id) sender {
NSLog(#"Function called. Sender tag number: %i", [sender tag]);
}
Method 2:
- (void) generateView {
container = [[UIScrollView alloc] initWithFrame: CGRectMake(10, 10, 500, 300)];
container.backgroundColor = [UIColor clearColor];
container.contentSize = CGSizeMake(500,1200);
container.showsVerticalScrollIndicator = YES;
[container setScrollEnabled:TRUE];
container.backgroundColor = [UIColor redColor];
int row = 0;
int col = 0;
for (int i = 0; i < 5; i++) {
if(i % 4 == 0 && i != 0){
row++;
col = 0;
}
UIButton *b = [[UIButton alloc] initWithFrame: CGRectMake(col*120, row*120, 100, 100)];
NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:[NSString stringWithFormat:#"%#/images/items/%i.png", HOSTADDR, i ]]];
[b setBackgroundImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal];
[b setBackgroundColor: [UIColor colorWithRed:0x42/255.0f green:0x30/255.0f blue:0x27/255.0f alpha:1]];
[b setTag: i];
[b addTarget:mainViewController action:#selector(updateData:) forControlEvents:UIControlEventTouchUpInside];
[b setEnabled:TRUE];
[b setUserInteractionEnabled:TRUE];
[container addSubview:b];
col++;
}
[self addSubview:container];
}
What I really need is method 2, cuz I want to call the updateData in mainViewController, but no matter how i tried, the button is not calling the function thats supposed to be called. Any idea?
EDIT:
This is how I called the view class
- (void) loadContent: (id) sender {
[self removeSubmenus];
switch ([sender tag]) {
case 2001:
{
MainView *mainView = [[MainView alloc] initWithSubmenu:CGRectMake(420, 85, 0, 0)];
[self.view addSubview:mainView];
break;
}
default:
break;
}
}
You should set delaysContentTouches to YES on the UIScrollView.
You're also leaking a bunch of memory. Make sure you're releasing both the UIButton (b) and NSData (imageData) objects as soon as you're done with them.
--
EDIT: I tried your code and it works fine. But it seems you wanted all this code in a UIView, so I threw together a quick sample.
TestView.h
#import <UIKit/UIKit.h>
#interface TestView : UIView {}
#end
TestView.m
#import "TestView.h"
#implementation TestView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
UIScrollView *container = [[UIScrollView alloc] initWithFrame: CGRectMake(10, 10, 500, 300)];
int row = 0;
int col = 0;
for (int i = 0; i < 5; i++) {
if(i % 4 == 0 && i != 0){
row++;
col = 0;
}
UIButton *b = [[UIButton alloc] initWithFrame: CGRectMake(col*120, row*120, 100, 100)];
[b setBackgroundColor: [UIColor colorWithRed:0x42/255.0f green:0x30/255.0f blue:0x27/255.0f alpha:1]];
[b setTag: i];
[b addTarget:self action:#selector(testFunction:) forControlEvents:UIControlEventTouchUpInside];
[container addSubview:b];
[b release];
col++;
}
[self addSubview:container];
}
return self;
}
- (void) testFunction: (id) sender {
NSLog(#"Function called. Sender tag number: %i", [sender tag]);
}
- (void)dealloc {
[super dealloc];
}
#end
TestController.h
#interface TestController : UIViewController { }
#end
TestController.m:
#import "TestController.h"
#import "TestView.h"
#implementation TestController
- (void) generateView {
TestView *tv = [[TestView alloc]initWithFrame:[self.view frame]];
[self.view addSubview:tv];
[tv release];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self generateView];
}
- (void)dealloc {
[super dealloc];
}
#end
Try adding this code to your method
container.delaysContentTouches = NO;
container.canCancelContentTouches = NO;
Pls modify your code to avoid memory leaks. Make sure you delete objects that you take ownership of.
Try this,
[b addTarget:mainViewController.view action:#selector(updateData:) forControlEvents:UIControlEventTouchUpInside];

Thumbnail grid of images

How does one create a dynamic thumbnail grid?
How is a grid created with thumbnails of images like the photo app on iphone?
How are these spaces arranged dynamically? e.g. adding and removing thumbnails.
this is my simple grid view app
- (void)viewDidAppear:(BOOL)animated {
[[Grid_ViewAppDelegate sharedAppDelegate] hideLoadingView];
temp = temp+1;
if (temp ==1){
NSLog(#"temp:%d",temp);
int n = 20; //Numbers of array;
NSArray *t = [[NSArray alloc] initWithObjects:#"calpie.gif",#"chrysler_electric.png",#"chrysler_fiat_cap.gif",#"cleanup.gif",#"ecylindri.gif",#"elect08.png",#"globe.gif",#"heat.gif",#"insur.gif"
,#"jobs.gif",#"office.gif",#"opec1.gif",#"orng_cap.gif",#"poll.gif",#"pollen.gif",#"purbar.gif",#"robinson.gif",#"robslink_cap.gif",#"scot_cap.gif",#"shoes.gif",nil];
myScrollView.contentSize = CGSizeMake(320, 460+n*2);
myScrollView.maximumZoomScale = 4.0;
myScrollView.minimumZoomScale = 1;
myScrollView.clipsToBounds = YES;
myScrollView.delegate = self;
NSString *mxiURL = #"http://meta-x.com/biflash/images/";
int i =0,i1=0;
while(i<n){
int yy = 4 +i1*79;
for(int j=0; j<4;j++){
if (i>=n) break;
CGRect rect;
rect = CGRectMake(4+79*j, yy, 75, 75);
UIButton *button=[[UIButton alloc] initWithFrame:rect];
[button setFrame:rect];
NSString *nn = [mxiURL stringByAppendingString:[t objectAtIndex:i]];
UIImage *buttonImageNormal=[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: nn]]];
[button setBackgroundImage:buttonImageNormal forState:UIControlStateNormal];
button.tag =i;
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside ];
//[self.view addSubview:button];
[myScrollView addSubview:button];
//[buttonImageNormal release];
[button release];
i++;
//
}
i1 = i1+1;
//i=i+4;
}
}
}
in AppDelegate
+ (Grid_ViewAppDelegate *)sharedAppDelegate
{
return (Grid_ViewAppDelegate *)[UIApplication sharedApplication].delegate;
}
- (void)showLoadingView
{
if (loadingView == nil)
{
loadingView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 480.0)];
loadingView.opaque = NO;
loadingView.backgroundColor = [UIColor grayColor];
loadingView.alpha = 0.5;
UIActivityIndicatorView *spinningWheel = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(142.0, 222.0, 37.0, 37.0)];
[spinningWheel startAnimating];
spinningWheel.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
[loadingView addSubview:spinningWheel];
[spinningWheel release];
CGRect label = CGRectMake(142.0f, 255.0f, 71.0f, 20.0f);
lblLoading = [[UILabel alloc] initWithFrame:label];
lblLoading.textColor = [UIColor whiteColor];
lblLoading.font = [UIFont boldSystemFontOfSize:14];
// UILabel
lblLoading.backgroundColor =[UIColor clearColor];
[lblLoading setText:#"Loading..."];
//[lblLoading setTextAlignment:UITextAlignmentCenter];
[loadingView addSubview:lblLoading];
}
[window addSubview:loadingView];
}
- (void)hideLoadingView
{
[loadingView removeFromSuperview];
}
definitely if u apply this logic. u get succeed