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];
Related
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
I have to create a multiple textfield dynamically on scrollview in ipad app. textfield created successfully and i use popup view on clicked textfield but when i clicked on textfield i dont get the Tag of Textfield. i get tag of last textfield so i cant set the text on the current textfield.
Following code i used...
int j = 430;
int k = 413;
int RB = 423;
for (int i=0; i<[appDelegate.questions count]; i++) {
imgTxtQue = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"textbox.png"]];
imgTxtQue.frame = CGRectMake(267, k, 490, 60);
// UIImageView *imgRatingBtn = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#""]];
// imgRatingBtn.frame = CGRectMake(633, RB, 102, 39);
//ratingButton1.hidden = NO;
ratingButton1 = [[UIButton alloc] initWithFrame:CGRectMake(633, RB, 102, 39)];
[ratingButton1 setImage:[UIImage imageNamed:#"rating_selected.png"] forState:UIControlStateNormal];
txtQuestions = [[UITextField alloc] initWithFrame:CGRectMake(296, j, 429, 24)];
//txtQuestions.tag = i;
[txtQuestions setTag:i];
NSLog(#"%d", txtQuestions.tag);
txtQuestions.delegate = self;
[txtQuestions setPlaceholder:[[appDelegate.questions objectAtIndex:i] objectForKey:#"question"]];
txtQuestions.borderStyle = UITextBorderStyleNone;
// txtQuestions.background = imgTxtQue.image;
[scrView addSubview:imgTxtQue];
[scrView addSubview:ratingButton1];
[scrView addSubview:txtQuestions];
j = j+50;
k = k+50;
RB = RB+50;
}
-(void)loadQuestion
{
txtQuestionOne.hidden=NO;
imgTxtQue.hidden=NO;
CGRect aFrame1 = imgTxtQue.frame;
aFrame1.size.width = aFrame1.size.width + 200;
// aFrame.size.height = newHeight;
NSString *strQue = [NSString stringWithFormat:#"%#",[[appDelegate.questions objectAtIndex:0] objectForKey:#"question"]];
CGSize newSize1 = [strQue sizeWithFont: [UIFont fontWithName: #"TrebuchetMS" size: 12] ];
if (strQue.length > 42) {
imgTxtQue.frame = CGRectMake(267, 413, newSize1.width+353, 60);
[txtQuestionOne setFrame:CGRectMake(294, 430, newSize1.width+350, 24)];
ratingButton1.frame = CGRectMake(855, 423, 102, 39);
ratingLabel1.frame = CGRectMake(900, 430, 42, 21);
}
[txtQuestionOne setPlaceholder:[[appDelegate.questions objectAtIndex:0] objectForKey:#"question"]];
appDelegate.dynamicQues =[[appDelegate.questions objectAtIndex:0] objectForKey:#"question"];
NSLog(#"current q1 %#", [[appDelegate.questions objectAtIndex:0] objectForKey:#"question"]);
if ([[[appDelegate.questions objectAtIndex:0] objectForKey:#"permission"] isEqualToString:#"1"]) {
ratingButton1.hidden=NO;
ratingLabel1.hidden=NO;
}
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
BOOL editing=YES;
for (UIImageView *img in ViewPost.subviews)
{
if ([img isKindOfClass:[UIImageView class]])
{
if (img.tag==textField.tag)
{
[img setImage:[UIImage imageNamed:#"Redtextbox.png"]];;
}
else{
if (img.tag!=0) {
if (img.tag != 10) {
[img setImage:[UIImage imageNamed:#"textbox.png"]];
}
else
{
[img setImage:[UIImage imageNamed:#"inputbox.png"]];
}
}
}
}
}
if (textField==txtcategory) {
[textField resignFirstResponder];
appDelegate.category=YES;
editing=NO;
touchflag=1;
[self performSelectorOnMainThread:#selector(CategoryListClick) withObject:nil waitUntilDone:YES];
//[self CategoryListClick];
return NO;
}
if (textField==txtsubcategory) {
appDelegate.category=NO;
editing=NO;
[self performSelectorOnMainThread:#selector(CategoryListClick) withObject:nil waitUntilDone:YES];
}
if (txtQuestions.tag) {
// if (textField==txtQuestions) {
editing=NO;
index=txtQuestions.tag;
NSLog(#"%d",txtQuestions.tag);
touchflag = 1;
[self performSelectorOnMainThread:#selector(loadAnswers) withObject:nil waitUntilDone:YES];
// }
}
-(void)loadAnswers{
if (touchflag==1) {
[Name resignFirstResponder];
[Email resignFirstResponder];
[txtCityCode resignFirstResponder];
[txtcategory resignFirstResponder];
[txtTitle resignFirstResponder];
[txtQuestions resignFirstResponder];
[txtsubcategory resignFirstResponder];
SubcategoryPopViewController *objPopview = [[SubcategoryPopViewController alloc]initWithNibName:#"SubcategoryPopViewController" bundle:nil];
objPopview.delegate = self;
objPopview.index=txtQuestions.tag;
popView =[[UIPopoverController alloc]initWithContentViewController:objPopview];
[self RescheduleTimer];
[popView presentPopoverFromRect:imgTxtQue.frame inView:ViewPost permittedArrowDirections:0 animated:NO];
[popView setPopoverContentSize:CGSizeMake(376, 260)];
}
}
-(void) didSelectAnswer{
touchflag=0;
[popView dismissPopoverAnimated:YES];
[self RescheduleTimer];
if (appDelegate.ansDynamic==YES) {
// txtQuestionOne.text=appDelegate.answerOne;
if (txtQuestions.tag) {
txtQuestions.text = appDelegate.answerDynamic;
}
appDelegate.ansDynamic=NO;
questionIndex=txtQuestions.tag;
if (![ratingButton1 isHidden]) {
ratingButton1.enabled=YES;
RatingPopViewController *objPopview = [[RatingPopViewController alloc]initWithNibName:#"RatingPopViewController" bundle:nil];
objPopview.index=txtQuestions.tag;
objPopview.checkedCell=ratingLabel1.text;
objPopview.QuestionText=appDelegate.answerDynamic;
objPopview.delegate=self;
popSweepStakes =[[UIPopoverController alloc]initWithContentViewController:objPopview];
[popSweepStakes presentPopoverFromRect:ratingButton1.frame inView:ViewPost permittedArrowDirections:UIPopoverArrowDirectionRight animated:YES];
[popSweepStakes setPopoverContentSize:CGSizeMake(300, 400)];
}
return;
}
In the above code i get the tag correctly but when i use tag on other mathod then i only get the last textfields tag.
Thanks,
Rahul Virja
You overwrite txtQuestions variable.
Declare a class attribute like this NSMutableArray * _textFieldArray. (It's import declare a NSMutableArray object for add your textField).
In the init method of your class allocate and init your array: _textFieldArray = [[NSmutableArray alloc]init].
In your for statement use the following code for allocate a textField:
UItextField * txtQuestions = [[UITextField alloc] initWithFrame:CGRectMake(296, j, 429, 24)];
After setting all your property on txtQuestions object, add it to the array
[_textFieldArray addObject:txtQuestions]
When you need for a textfield use this code:
[_textFieldArray objectAtIndex:txtQuestions.tag]
Is it Clear?
I have a view with 3 ratings bars on it.
How do I tell them apart in the code? Right now if I change the top one it sees it fine but if I then change either or the other two it cannot separate them from one another.
The code is from git https://github.com/dyang/DYRateView
- (void)changedToNewRate:(NSNumber *)rate {
NSString *rating = [NSString stringWithFormat:#"Rate: %d", rate.intValue];
NSLog(#"rating: %#",rating);
}
This is where is sees the changing.
And this is the .m file
#import "Survey.h"
#implementation Survey
#synthesize btnSubmit;
- (void)setUpEditableRateView {
DYRateView *rateService = [[DYRateView alloc] initWithFrame:CGRectMake(0, 55, self.view.bounds.size.width, 40) fullStar:[UIImage imageNamed:#"StarFullLarge#2x.png"] emptyStar:[UIImage imageNamed:#"StarEmptyLarge#2x.png"]];
rateService.padding = 20;
rateService.alignment = RateViewAlignmentCenter;
rateService.editable = YES;
rateService.delegate =self;
[scroller addSubview:rateService];
[rateService release];
DYRateView *rateFood = [[DYRateView alloc] initWithFrame:CGRectMake(0, 130, self.view.bounds.size.width, 40) fullStar:[UIImage imageNamed:#"StarFullLarge#2x.png"] emptyStar:[UIImage imageNamed:#"StarEmptyLarge#2x.png"]];
rateFood.padding = 20;
rateFood.alignment = RateViewAlignmentCenter;
rateFood.editable = YES;
rateFood.delegate = self;
[scroller addSubview:rateFood];
[rateFood release];
DYRateView *rateCleanliness = [[DYRateView alloc] initWithFrame:CGRectMake(0, 200, self.view.bounds.size.width, 40) fullStar:[UIImage imageNamed:#"StarFullLarge#2x.png"] emptyStar:[UIImage imageNamed:#"StarEmptyLarge#2x.png"]];
rateCleanliness.padding = 20;
rateCleanliness.alignment = RateViewAlignmentCenter;
rateCleanliness.editable = YES;
rateCleanliness.delegate = self;
[scroller addSubview:rateCleanliness];
[rateCleanliness release];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (void)changedToNewRate:(NSNumber *)rate {
NSString *rating = [NSString stringWithFormat:#"Rate: %d", rate.intValue];
NSLog(#"rating: %#",rating);
}
- (IBAction)btnSubmit:(id)sender{
}
-(IBAction)mainMenu{
[self dismissModalViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
[scroller setScrollEnabled:YES];
[scroller setContentSize:CGSizeMake(320, 600)];
scroller.BackgroundColor = [UIColor clearColor];
[self setUpEditableRateView];
[btnSubmit useGreenConfirmStyle];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
UPDATE
ok with the new code I added an if statement
- (void)rateView:(DYRateView *)rateView changedToNewRate:(NSNumber *)rate {
NSString *barName = [NSString stringWithFormat:#"%#", rateView];
if (barName == #"rateView1") {
NSString *bar1 = [NSString stringWithFormat:#"Rate: %d", rate.intValue];
NSLog(#"bar 1: %#",bar1);
}else if(barName == #"rateView2"){
NSString *bar2 = [NSString stringWithFormat:#"Rate: %d", rate.intValue];
NSLog(#"bar 2: %#",bar2);
}else{
NSLog(#"NO BAR: %#",barName);
}
self.rateLabel.text = [NSString stringWithFormat:#"Rate: %d", rate.intValue];
}
It works however Instead of getting back "rateView1" or 2 or 3. I get back
NO BAR: <DYRateView: 0x78229b0; frame = (0 40; 320 20); opaque = NO; layer =
<CALayer:0x7824900>>
Which is correct in nature but I was hoping for the name of the rateView such as "rateView1"
SOLUTION:
in .h file #property your 2 or 3 bars
#property(nonatomic, retain) DYRateView *rateView1,*rateView2;
in .m #synthesize them
#synthesize rateView1;
#synthesize rateView2;
then
(void)setUpEditableRateView {
rateView1 = [[DYRateView alloc] initWithFrame:CGRectMake(0, 40, self.view.bounds.size.width, 20) fullStar:[UIImage imageNamed:#"StarFullLarge.png"] emptyStar:[UIImage imageNamed:#"StarEmptyLarge.png"]];
rateView1.padding = 20;
rateView1.alignment = RateViewAlignmentCenter;
rateView1.editable = YES;
rateView1.delegate = self;
[self.view addSubview:rateView1];
[rateView1 release];
rateView2 = [[DYRateView alloc] initWithFrame:CGRectMake(0, 100, self.view.bounds.size.width, 20) fullStar:[UIImage imageNamed:#"StarFullLarge.png"] emptyStar:[UIImage imageNamed:#"StarEmptyLarge.png"]];
rateView2.padding = 20;
rateView2.alignment = RateViewAlignmentCenter;
rateView2.editable = YES;
rateView2.delegate = self;
[self.view addSubview:rateView2];
[rateView2 release];
// Set up a label view to display rate
self.rateLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 80, self.view.bounds.size.width, 20)] autorelease];
self.rateLabel.textAlignment = UITextAlignmentCenter;
self.rateLabel.text = #"Tap above to rate";
[self.view addSubview:self.rateLabel];
}
Then Finally
- (void)rateView:(DYRateView *)rateView changedToNewRate:(NSNumber *)rate {
if (rateView == rateView1) {
NSString *bar1 = [NSString stringWithFormat:#"Rate: %d", rate.intValue];
NSLog(#"bar 1: %#",bar1);
}else if(rateView == rateView2){
NSString *bar2 = [NSString stringWithFormat:#"Rate: %d", rate.intValue];
NSLog(#"bar 2: %#",bar2);
}else{
NSLog(#"NO BAR: %#",rateView);
}
self.rateLabel.text = [NSString stringWithFormat:#"Rate: %d", rate.intValue];
}
Thanks for using DYRateView!
The current version of DYRateView doesn't support listening to multiple instances all at the same time, but that doesn't mean that we can't do that. :)
If you don't mind updating the source code, you can find a method named notifyDelegate in DYRateView.m, and change [self.delegate performSelector:#selector(changedToNewRate:) withObject:[NSNumber numberWithFloat:self.rate]] to something like [self.delegate performSelector:#selector(rateView:changedToNewRate:) withObject:self withObject:[NSNumber numberWithFloat:self.rate]]. In this way you are able to pass the rateView itself as a parameter to its listener.
I haven't tried the above code yet as I don't have access to my Mac at this point, but I think this should give you an idea regarding how to achieve your goal.
I just set the tag for each of my rateviews to tell them apart, so in your example, I add a tag to each one:
#define serviceTag 1
#define foodTag 2
#define cleanlinessTag 3
- (void)setUpEditableRateView {
DYRateView *rateService = [[DYRateView alloc] initWithFrame:CGRectMake(0, 55, self.view.bounds.size.width, 40) fullStar:[UIImage imageNamed:#"StarFullLarge#2x.png"] emptyStar:[UIImage imageNamed:#"StarEmptyLarge#2x.png"]];
rateService.padding = 20;
rateService.alignment = RateViewAlignmentCenter;
rateService.editable = YES;
rateService.tag = serviceTag;
rateService.delegate =self;
[scroller addSubview:rateService];
[rateService release];
DYRateView *rateFood = [[DYRateView alloc] initWithFrame:CGRectMake(0, 130, self.view.bounds.size.width, 40) fullStar:[UIImage imageNamed:#"StarFullLarge#2x.png"] emptyStar:[UIImage imageNamed:#"StarEmptyLarge#2x.png"]];
rateFood.padding = 20;
rateFood.alignment = RateViewAlignmentCenter;
rateFood.editable = YES;
rateFood.tag = foodTag;
rateFood.delegate = self;
[scroller addSubview:rateFood];
[rateFood release];
DYRateView *rateCleanliness = [[DYRateView alloc] initWithFrame:CGRectMake(0, 200, self.view.bounds.size.width, 40) fullStar:[UIImage imageNamed:#"StarFullLarge#2x.png"] emptyStar:[UIImage imageNamed:#"StarEmptyLarge#2x.png"]];
rateCleanliness.padding = 20;
rateCleanliness.alignment = RateViewAlignmentCenter;
rateCleanliness.editable = YES;
rateCleanliness.delegate = self;
rateCleanliness.tag = cleanlinessTag;
[scroller addSubview:rateCleanliness];
[rateCleanliness release];
}
Then, in the delegate method, you can just check the tag:
- (void)rateView:(DYRateView *)rateView changedToNewRate:(NSNumber *)rate {
switch (rateView.tag) {
case foodTag:
// Do something for food
break;
case serviceTag:
// Do something for service
break;
case cleanlinessTag:
// Do something for cleanliness
break;
default:
break;
}
}
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.
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