calling selectRow:inComponent:animated: method - ios5

I have 2 UIpicker view in my app and I want the pickers to show the last chosen row after i saved my data. I am using this selectRow:inComponent:animated: method, but where do I exactly call this method?
in viewDidLoad:
if (self.pickerView == nil) {
self.pickerView = [[UIPickerView alloc] init];
self.pickerView.delegate = self;
self.pickerView.showsSelectionIndicator = YES;
in pickerView:viewForRow:forComponent:reusingView:
if (component == 0)
{
for (int j =20; j<=200; j++)
{
NSString* myString = [NSString stringWithFormat:#"%d",j];
[myArray addObject:myString];
}
UILabel *weightLabel0 = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, 100, 32)];
Label0.text = [myArray objectAtIndex:row];
Label0.textAlignment = UITextAlignmentLeft;
Label0.backgroundColor = [UIColor clearColor];
[rowView insertSubview:weightLabel0 atIndex:1];
return rowView;
}
and i have a method here:
-(void) refreshPicker
{
NSArray* mArray = [self.myTextField.text componentsSeparatedByString:#"."];
NSNumber* str1 = [mArray objectAtIndex:0];
int selectRow1 = [str1 intValue]-20;
NSNumber* str2 = [mArray objectAtIndex:1];
int selectRow = [str2 intValue];
if (selectRow == 0) {
int selectRow2 = 0;
[self.pickerView selectRow:selectRow2 inComponent:1 animated:NO];
}
else if (selectRow == 5) {
int selectRow2 = 1;
[self.pickerView selectRow:selectRow2 inComponent:1 animated:NO];
}
[self.pickerView selectRow:selectRow1 inComponent:0 animated:NO];
[pickerView_ reloadAllComponents];
}
how should i put this together? if i call this method at, for instance, viewDidLoad, nothing happens. help please =)

I have came up with an idea. since my pickers only create the items when the textfield is being called, i.e. becomes first responder, hence, i call my refreshPicker method inside textFieldDidBeginEditing. and don't forget to set the textfield delegate to self. =) to those who encounters my problem, cheers.

Related

Identifying an UIImageView without tag

I have some generic generated ImageViews in a scrollView each of these images have 2 gestureRecognizer for single/double tapping on the ImageView. Now my problem is how to identify whether the ImageView was tapped for first or second time. In some scenarios it's easy to use the tag of an ImageView, but I have two different gestureRecognizer on each ImageView and every gestureRecognizer uses a different identification method based on the tag number, to identify the image.
Here I generate the ImageViews dynamically:
-(void) initLevels{
_level = [Level alloc];
_unit = [Unit alloc];
self->_units = [[NSMutableArray alloc] init];
_keys = [[NSMutableArray alloc] init]
;
int x = 0;
int y = 0;
int i = 0;
for (NSObject *object in self->_levels) {
if ([object isKindOfClass:_level.class] && i != 0) {
x = x + MARGIN_RIGHT + OBJECT_WIDTH;
y = 0;
}
else if ([object isKindOfClass:_unit.class]){
_unit = (Unit *) object;
[self->_units addObject:_unit.description];
UIImageView *imageView = [[UIImageView alloc] initWithImage:self.box];
[imageView setFrame:CGRectMake(x, y, OBJECT_WIDTH, BOX_HEIGHT)];
imageView.highlighted = TRUE;
imageView.tag = i; //when this is not outlined the gestureRecognizer for singleTapping works but on the other hand the double tap gestureRecognizer just works for the first object, because its' tag is set on 0.
UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(unitDoubleTapped:)];
doubleTapGesture.numberOfTapsRequired = 2;
imageView.userInteractionEnabled = YES;
[imageView addGestureRecognizer:doubleTapGesture];
UITapGestureRecognizer *singleTapGesture =
[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(unitSingleTapped:)];
singleTapGesture.numberOfTapsRequired = 1;
//telling the singleTapGesture to fail the doubleTapGesture, so both doesn't fire at the same time
[singleTapGesture requireGestureRecognizerToFail:doubleTapGesture];
[imageView addGestureRecognizer:singleTapGesture];
UILabel *labelHeadline = [[UILabel alloc] initWithFrame:CGRectMake(5, 2, 220, 20)];
[labelHeadline setFont:[UIFont boldSystemFontOfSize:12]];
labelHeadline.textAlignment = NSTextAlignmentCenter;
[labelHeadline setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:0]];
labelHeadline.text = _unit.headline;
labelHeadline.numberOfLines = 0;
[labelHeadline sizeToFit];
UILabel *labelPrice = [LabelUtils deepLabelCopy:labelHeadline withText:[NSString stringWithFormat:#"Price: %#",_unit.price] withFrame:NO];
[labelPrice setTextAlignment:NSTextAlignmentLeft];
[labelPrice setFrame:CGRectMake(labelHeadline.frame.origin.x, labelHeadline.frame.origin.y + labelHeadline.frame.size.height + 2, 220, 20)];
UILabel *labelCRM = [LabelUtils deepLabelCopy:labelHeadline withText:[NSString stringWithFormat:#"CRM: %#", _unit.crm] withFrame:NO];
[labelCRM setTextAlignment:NSTextAlignmentLeft];
[labelCRM setFrame:CGRectMake(labelPrice.frame.origin.x, labelPrice.frame.origin.y + labelPrice.frame.size.height + 2, 220, 20)];
UITextView *textView= [[UITextView alloc] initWithFrame:CGRectMake(0,0, OBJECT_WIDTH, OBJECT_HEIGHT)];
[textView addSubview:labelHeadline];
[textView addSubview:labelPrice];
[textView addSubview:labelCRM];
[textView setUserInteractionEnabled:NO];
[textView setEditable:NO];
textView.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0];
textView.textAlignment = NSTextAlignmentLeft;
[imageView addSubview:textView];
[_scrollView addSubview:imageView];
y = y + MARGIN_BOTTOM + BOX_HEIGHT;
}
[self->_keys addObject:[NSNumber numberWithInt:i]];
i++;
}//remove the last keys which are to much in the _keys array
while ([self->_keys count] > ([self->_units count])) {
[_keys removeLastObject];
i--;
}
self.contents = [NSDictionary dictionaryWithObjects:self->_units forKeys:_keys];
}
Here is the code for the two gesture Recognizer
-(void)unitDoubleTapped:(UIGestureRecognizer *)gestureRecognizer{
self->_unitViewForDoubleTapIdentification = (UIImageView *)gestureRecognizer.view;
switch (self->_unitViewForDoubleTapIdentification.tag) {
case 0:
[_unitViewForDoubleTapIdentification setHighlightedImage:self.transparentBox];
self->_unitViewForDoubleTapIdentification.tag = 1;
break;
case 1:
[_unitViewForDoubleTapIdentification setHighlightedImage:self.box];
self->_unitViewForDoubleTapIdentification.tag = 0;
break;
default:
break;
}
}
and Here the singleTap
- (IBAction)unitSingleTapped:(id)sender {
[self dismissAllPopTipViews];
UIGestureRecognizer *gestureRecognizer = [UIGestureRecognizer alloc];
gestureRecognizer = (UIGestureRecognizer *)sender;
UIImageView *imageView = [[UIImageView alloc] init];
imageView = (UIImageView *)gestureRecognizer.view;
if (sender == _currentPopTipViewTarget) {
// Dismiss the popTipView and that is all
self.currentPopTipViewTarget = nil;
}
NSString *contentMessage = nil;
UIImageView *contentView = nil;
NSNumber *key = [NSNumber numberWithInt:imageView.tag];
id content = [self.contents objectForKey:key];
if ([content isKindOfClass:[NSString class]]) {
contentMessage = content;
}
else {
contentMessage = #"A large amount ot text in this bubble\najshdjashdkgsadfhadshgfhadsgfkasgfdasfdhasdkfgaodslfgkashjdfg\nsjfkasdfgkahdjsfghajdsfgjakdsfgjjakdsfjgjhaskdfjadsfgjdsfahsdafhjajdskfhadshfadsjfhadsjlfkaldsfhfldsa\ndsfgahdsfgajskdfgkafd";
}
NSArray *colorScheme = [_colorSchemes objectAtIndex:foo4random()*[_colorSchemes count]];
UIColor *backgroundColor = [colorScheme objectAtIndex:0];
UIColor *textColor = [colorScheme objectAtIndex:1];
CMPopTipView *popTipView;
if (contentView) {
popTipView = [[CMPopTipView alloc] initWithCustomView:contentView];
}
else {
popTipView = [[CMPopTipView alloc] initWithMessage:contentMessage];
}
[popTipView presentPointingAtView:imageView inView:self.view animated:YES];
popTipView.delegate = self;
popTipView.disableTapToDismiss = YES;
popTipView.preferredPointDirection = PointDirectionUp;
if (backgroundColor && ![backgroundColor isEqual:[NSNull null]]) {
popTipView.backgroundColor = backgroundColor;
}
if (textColor && ![textColor isEqual:[NSNull null]]) {
popTipView.textColor = textColor;
}
popTipView.animation = arc4random() % 2;
popTipView.has3DStyle = (BOOL)(arc4random() % 2);
popTipView.dismissTapAnywhere = YES;
[popTipView autoDismissAnimated:YES atTimeInterval:3.0];
[_visiblePopTipViews addObject:popTipView];
self.currentPopTipViewTarget = sender;
}
Hope you can help me, thanks in advance.
that's a lot of code to go through.. but I add more identifiers to UIViews (ie other than the tag identifier) by using obj-c runtime associative references..
So this is a category I attach to my UIView:
#import "UIView+Addons.h"
#import <objc/runtime.h>
#define kAnimationDuration 0.25f
#implementation UIView (Addons)
static char infoKey;
static char secondaryInfoKey;
-(id)info {
return objc_getAssociatedObject(self, &infoKey);
}
-(void)setInfo:(id)info {
objc_setAssociatedObject(self, &infoKey, info, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(id)secondaryInfo {
return objc_getAssociatedObject(self, &secondaryInfoKey);
}
-(void)setSecondaryInfo:(id)info {
objc_setAssociatedObject(self, &secondaryInfoKey, info, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#end
here is an example of my own code where I use the above to address a problem similar to the one you're facing:
if (![[view info] boolValue]) { // not selected?
self.moveToFolderNumber = [view secondaryInfo];
[view setInfo:#YES];
}

Multiple UITextfield Create Dynamically in iphone sdk

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?

iPhone/Objective-c - Gaining access to a previous ViewController from a subview?

How do I access a previous view controller while in a subview? Because I'm able to perform actions but I'm just not able to use self.[my main view controller].
This is my code, for testing purposes:
PhotoViewController.m
-(IBAction)likeButton:(UIButton *)sender
{
//this part works
NSString *num = #"2";
self.label.text = [NSString stringWithFormat:#"%# + %#",
self.label.text,
num];
//this part doesn't work
//switch over to the third view to see if it worked
self.tabBarController.selectedIndex = 0;
}
I have a UITabBarController and one of its view controllers has a UIScrollView. Inside of the UIScrollView is a PhotoViewController object.
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch
MyTabBarViewController *vc2 = [[MyTabBarViewController alloc] init];
SecondViewController *vc3 = [[SecondViewController alloc] init];
controller = [[DemoAppViewController alloc] init];
controller.view.frame = CGRectMake(0, 20, 320, 460);
controller.title = #"Intro Screen";
vc2.title = #"Explore";
vc3.title = #"Send a Pic";
UITabBarController *tbc = [[UITabBarController alloc] init];
tbc.viewControllers = [NSArray arrayWithObjects:controller, vc2, vc3, nil];
[controller release];
[vc2 release];
[vc3 release];
[self.window addSubview:tbc.view];
[self.window makeKeyAndVisible];
return YES;
}
Also, my TabBarViewController.m //not my actual UITabBarController though, wording is confusing
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
arrayCount = [array count];
scroller.delegate=self;
scroller.pagingEnabled=YES;
scroller.directionalLockEnabled=YES;
scroller.showsHorizontalScrollIndicator=NO;
scroller.showsVerticalScrollIndicator=NO;
//should have an array of photo objects and the number of objects, correct?
scrollWidth = 0;
scroller.contentSize=CGSizeMake(arrayCount*scroller.frame.size.width, scroller.frame.size.height);
for (int i = 0; i < arrayCount;i++) {
PhotoViewController *pvc = [[PhotoViewController alloc] initWithNibName:#"PhotoViewController" bundle:nil];
UIImageView *scrollImageView = [[UIImageView alloc] initWithFrame:CGRectOffset(scroller.bounds, scrollWidth, 0)];
CGRect rect = scrollImageView.frame;
pvc.view.frame = rect;
pvc.label.textColor = [UIColor whiteColor];
id individualPhoto = [array objectAtIndex:i];
NSLog(#"%#",individualPhoto);
NSArray *keys=[individualPhoto allKeys];
NSLog(#"%#",keys);
NSString *imageURL=[individualPhoto objectForKey:#"source"];
NSURL *url = [NSURL URLWithString:imageURL];
NSData *data = [NSData dataWithContentsOfURL:url];
pvc.imageView.image = [[UIImage alloc] initWithData:data];
pvc.label.text = [individualPhoto objectForKey:#"id"];
[scroller addSubview:pvc.view];
[scrollImageView release];
//[pvc release];
scrollWidth += scroller.frame.size.width;
}
if (arrayCount > 3) {
pageControl.numberOfPages=3;
} else {
pageControl.numberOfPages=arrayCount;
}
pageControl.currentPage=0;
}
If a UIView subclass needs to message a controller above itself, a common (and often recommended?) way to do this is to have the view subclass implement the delegate protocol (a weak linked instance variable pointing to the view controller that you want to use). The view controller should then set itself as the delegate of the view when that view is being initialize.
Try defining this method in your PhotoViewController:
+ (YOURTABBARCONTROLLER*)parentTabBarController:(UIResponder*)view {
id nextResponder = nil;
id v = view;
while (nextResponder = [v nextResponder]) {
NSLog(#"Found Responder: %#", nextResponder); //-- ADDED THIS
if ([nextResponder isKindOfClass:[YOURTABBARCONTROLLER class]])
return nextResponder;
v = nextResponder;
}
return nil;
}
it will traverse the responder chain and return the first controller of a given type that is found. Replace YOURTABBARCONTROLLER with your actual tab bar controller class and you should be able to have:
-(IBAction)likeButton:(UIButton *)sender
{
//this part works
NSString *num = #"2";
self.label.text = [NSString stringWithFormat:#"%# + %#",
self.label.text,
num];
[PhotoViewController parentTabBarController:self.view].selectedIndex = 0;
// self.tabBarController.selectedIndex = 0;
}
Updated
-(IBAction)likeCommentButton:(UIButton *)sender
{
//code goes here
TypeSomethingViewController *typeSomethingViewController = [[TypeSomethingViewController alloc] init];
typeSomethingViewController.delegate = self;
[self presentModalViewController:typeSomethingViewController animated:YES];
[typeSomethingViewController release];
}
-(void)typeSomethingViewController:(TypeSomethingViewController *)controller didTypeSomething:(NSString *)text
{
//NSLog(#"response: %#", controller);
NSString *commentID = self.label.text;
for(UIViewController *controller in [PhotoViewController parentTabBarController:self.parentViewController.view].viewControllers)
{
if([controller isKindOfClass:[DemoAppViewController class]])
{
DemoAppViewController *davc = (DemoAppViewController *)controller;
//[davc commentPicture:commentID :message];
[davc likePicture:commentID];
}
}
[PhotoViewController parentTabBarController:self.view].selectedIndex = 0;
[self dismissModalViewControllerAnimated:YES];
}
Try this out to switch to the first controller.
self.tabBarController.selectedViewController
= [self.tabBarController.viewControllers objectAtIndex:0];
Change the index value to switch to whichever controller you want to switch to.
The tabBarController should be a property of the app delegate.
Try accessing it with :
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication]
delegate];
appDelegate.tabBarController.selectedIndex = 0;
Unless you declare the same property in PhotoViewController, you won't be able to access it this way.
Try importing the app delegate header in PhotoViewController.h like so :
#import "MyAppDelegate"
then try this code above replacing tabBarController by tbc which, as the example suggests is the name given to this property.

Display A TTStyledTextLabel in a UITableView

How can I set a TTStyledTextLabel inside of a UITableView.
Each TTStyledTextLabel contains Some parsed HTML.
Heres what I have I realize its probably completely wrong.
TTStyledTextLabel* label = [[TTStyledTextLabel alloc] autorelease];
cell.textLabel.text = [TTStyledText textFromXHTML:tempString lineBreaks:YES URLs:YES];
App Crashes on launch. I think its because I am setting the .text property with something that is not text. However, I don't know what else to set.
The following code will do what you want. Unfortunately, however, I cannot figure out how to automatically set the height. If memory isn't an issue you could keep a seperate array of TTStyledTextLabels and reference their heights.
in your loadView:
CGRect cgRct2 = CGRectMake(0, 35, 320, 375); //define size and position of view
tblView = [[UITableView alloc] initWithFrame:cgRct2 style:UITableViewStylePlain];
tblView.dataSource = [self constructDataSource];
tblView.delegate = self;
//[tblView reloadData];
[myView addSubview:tblView];
in your class:
-(TTListDataSource *)constructDataSource {
NSLog(#"constructDataSource");
NSMutableArray * namesArray = [[NSMutableArray alloc] init];
//ADD ITEMS
[namesArray addObject:[TTStyledText textFromXHTML:[NSString stringWithString:#"some XHTML"]]];
TTListDataSource * dataSource = [[TTListDataSource alloc] init];
for (int i = 0; i < [namesArray count]; i++) {
TTStyledText * text = [namesArray objectAtIndex:i];
[dataSource.items addObject:[TTTableStyledTextItem itemWithText:text]];
}
[namesArray release];
return dataSource;
}

Weirdest occurrence ever, UIButton #selector detecting right button, doing wrong 'else_if'?

So I dynamically create 3 UIButtons (for now), with this loop:
NSMutableArray *sites = [[NSMutableArray alloc] init];
NSString *one = #"Constution Center";
NSString *two = #"Franklin Court";
NSString *three = #"Presidents House";
[sites addObject: one];
[one release];
[sites addObject: two];
[two release];
[sites addObject: three];
[three release];
NSString *element;
int j = 0;
for (element in sites)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//setframe (where on screen)
//separation is 15px past the width (45-30)
button.frame = CGRectMake(a, b + (j*45), c, d);
[button setTitle:element forState:UIControlStateNormal];
button.backgroundColor = [SiteOneController myColor1];
[button addTarget:self action:#selector(showCCView:)
forControlEvents:UIControlEventTouchUpInside];
[button setTag:j];
[self.view addSubview: button];
j++;
}
The #Selector method is here:
- (void) showCCView:(id) sender {
UIButton *button = (UIButton *)sender;
int whichButton = button.tag;
NSString* myNewString = [NSString stringWithFormat:#"%d", whichButton];
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.view.backgroundColor = [UIColor whiteColor];
UINavigationBar *cc = [SiteOneController myNavBar1:#"Constitution Center Content"];
UINavigationBar *fc = [SiteOneController myNavBar1:#"Franklin Court Content"];
UINavigationBar *ph = [SiteOneController myNavBar1:#"Presidents House Content"];
if (whichButton = 0)
{
NSLog(myNewString);
[self.view addSubview:cc];
}
else if (whichButton = 1)
{
NSLog(myNewString);
[self.view addSubview:fc];
}
else if (whichButton = 2)
{
NSLog(myNewString);
[self.view addSubview:ph];
}
}
Now, it is printing the correct button tag to NSLog, as shown in the method, however EVERY SINGLE BUTTON is displaying a navigation bar with "Franklin Court" as the title, EVERY SINGLE ONE, even though when I click button 0, it says "Button 0 clicked" in the console, but still performs the else if (whichButton = 1) code.
Am I missing something here?
You're using the = operator instead of the == operator in your conditions, which makes an assignment instead of a comparison.
Since the returned value of an assignment is the assigned value, first whichButton becomes 0 and that evaluates to false, and then whichButton becomes 1 and that evaluates to true, and no matter what you do you end up with the Franklin Court option.
You have a problem where you should have used == instead of =.
Instead of this:
if (whichButton = 0)
{
NSLog(myNewString);
[self.view addSubview:cc];
}
...
Try this:
if (whichButton == 0)
{
NSLog(myNewString);
[self.view addSubview:cc];
}
else if (whichButton == 1)
{
NSLog(myNewString);
[self.view addSubview:fc];
}
else if (whichButton == 2)
{
NSLog(myNewString);
[self.view addSubview:ph];
}
Or this:
NSLog (myNewString); //occurs in all cases.
switch (whichButton)
{
case 0:
[self.view addSubview:cc];
break;
case 1:
[self.view addSubview:fc];
break;
case 2:
[self.view addSubview:ph];
break;
default:
// optionally handle the case where the button's tag was not 0, 1, or 2.
}