I'm beginer. I saw another questions like mine, but I have different problem.
I have two questions:
1.I want use exist label to show correct answer.
In this app, after every answer, it only return image- wrong or correct answer.
There is no question text and correct answer text, how in usual quiz.
It's looks like on picture. Last image shows what I expect after changes.:
http://i62.tinypic.com/65ahe0.jpg
I think about change:
-use existing label, first under question text (UIButton *Answer1) to show correct answer under picture wrong/correct answer.
-show question text over correct answer text. I think I need change -QuestionText.hidden from YES for NO.
I wrote 90 questions in quiz, so I use:
arc4random() %89; // 0-89
It's work in Simulator.
I read here, arc4random () % working only to 51.
Will be a problem with it on device ?
Thank you for your help.
.m file:
#import "Game.h"
#interface Game ()
#end
#implementation Game
-(void)RightAnswer{
ScoreNumber = ScoreNumber + 1;
Score.text = [NSString stringWithFormat:#"%i", ScoreNumber];
NextCategory.hidden = NO;
Answer1.hidden = YES;
Answer2.hidden = YES;
Answer3.hidden = YES;
Answer4.hidden = YES;
QuestionText.hidden = YES;
CategorySelected.hidden = YES;
Result.hidden = NO;
Result.image = [UIImage imageNamed:#"rightanswer.png"];
}
-(void)WrongAnswer{
LivesNumber = LivesNumber - 1;
Lives.text = [NSString stringWithFormat:#"%i", LivesNumber];
NextCategory.hidden = NO;
Answer1.hidden = YES;
Answer2.hidden = YES;
Answer3.hidden = YES;
Answer4.hidden = YES;
QuestionText.hidden = YES;
CategorySelected.hidden = YES;
Result.hidden = NO;
Result.image = [UIImage imageNamed:#"wronganswer.png"];
if (LivesNumber == 0) {
Result.image = [UIImage imageNamed:#"gameover.png"];
NextCategory.hidden = YES;
Exit.hidden = NO;
GameInProgress = NO;
}
}
-(IBAction)Answer1:(id)sender{
if (Answer1Correct == YES) {
[self RightAnswer];
}
else{
[self WrongAnswer];
}
}
-(IBAction)Answer2:(id)sender{
if (Answer2Correct == YES) {
[self RightAnswer];
}
else{
[self WrongAnswer];
}
}
-(IBAction)Answer3:(id)sender{
if (Answer3Correct == YES) {
[self RightAnswer];
}
else{
[self WrongAnswer];
}
}
-(IBAction)Answer4:(id)sender{
if (Answer4Correct == YES) {
[self RightAnswer];
}
else{
[self WrongAnswer];
}
}
-(void)Category1{
switch (QuestionSelected) {
case 0:
QuestionText.text = [NSString stringWithFormat:#"What Team Won The 2012/2013 English Football Premier League?"];
[Answer1 setTitle:#"Manchester United" forState:UIControlStateNormal];
[Answer2 setTitle:#"Manchester City" forState:UIControlStateNormal];
[Answer3 setTitle:#"Liverpool" forState:UIControlStateNormal];
[Answer4 setTitle:#"Chelsea" forState:UIControlStateNormal];
Answer1Correct = YES;
break;
case 1:
QuestionText.text = [NSString stringWithFormat:#"Which City Hosted The 1992 Olympic Games?"];
[Answer1 setTitle:#"Norwich" forState:UIControlStateNormal];
[Answer2 setTitle:#"Barcelona" forState:UIControlStateNormal];
[Answer3 setTitle:#"Tokyo" forState:UIControlStateNormal];
[Answer4 setTitle:#"Lisbon" forState:UIControlStateNormal];
Answer2Correct = YES;
break;
case 2:
QuestionText.text = [NSString stringWithFormat:#"By What Score Did England Win The Ashes In The Summer of 2013?"];
[Answer1 setTitle:#"5-0" forState:UIControlStateNormal];
[Answer2 setTitle:#"4-0" forState:UIControlStateNormal];
[Answer3 setTitle:#"3-0" forState:UIControlStateNormal];
[Answer4 setTitle:#"2-0" forState:UIControlStateNormal];
Answer3Correct = YES;
break;
case 3:
QuestionText.text = [NSString stringWithFormat:#"What Team Won The NBA Playoff Finals In 2013?"];
[Answer1 setTitle:#"Golden State Warriors" forState:UIControlStateNormal];
[Answer2 setTitle:#"Memphis Grizzlies" forState:UIControlStateNormal];
[Answer3 setTitle:#"San Antonia Spurs" forState:UIControlStateNormal];
[Answer4 setTitle:#"Miami Heat" forState:UIControlStateNormal];
Answer4Correct = YES;
break;
default:
break;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
if (GameInProgress == NO) {
LivesNumber = 3;
ScoreNumber = 0;
GameInProgress = YES;
}
Result.hidden = YES;
Exit.hidden = YES;
NextCategory.hidden = YES;
Lives.text = [NSString stringWithFormat:#"%i", LivesNumber];
Score.text = [NSString stringWithFormat:#"%i", ScoreNumber];
Answer1Correct = NO;
Answer2Correct = NO;
Answer3Correct = NO;
Answer4Correct = NO;
CategoryLoaded = [[NSUserDefaults standardUserDefaults] integerForKey:#"CategorySaved"];
QuestionSelected = arc4random() %4;
switch (CategoryLoaded) {
case 1:
CategorySelected.text = [NSString stringWithFormat:#"Sport"];
[self Category1];
break;
case 2:
CategorySelected.text = [NSString stringWithFormat:#"Films"];
[self Category2];
break;
case 3:
CategorySelected.text = [NSString stringWithFormat:#"Music"];
[self Category3];
break;
case 4:
CategorySelected.text = [NSString stringWithFormat:#"Games"];
[self Category4];
break;
case 5:
CategorySelected.text = [NSString stringWithFormat:#"Geography"];
[self Category5];
break;
case 6:
CategorySelected.text = [NSString stringWithFormat:#"History"];
[self Category6];
break;
default:
break;
}
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
.h file:
NSInteger CategoryLoaded; //This has been updated from int as used in the videos, as this is used for saving and loading data. There have been some issue on the later devices using an int for this and not NSInteger
int QuestionSelected;
BOOL Answer1Correct;
BOOL Answer2Correct;
BOOL Answer3Correct;
BOOL Answer4Correct;
int ScoreNumber;
int LivesNumber;
BOOL GameInProgress;
#interface Game : UIViewController
{
IBOutlet UILabel *CategorySelected;
IBOutlet UILabel *QuestionText;
IBOutlet UIButton *Answer1;
IBOutlet UIButton *Answer2;
IBOutlet UIButton *Answer3;
IBOutlet UIButton *Answer4;
IBOutlet UIButton *NextCategory;
IBOutlet UIButton *Exit;
IBOutlet UILabel *Score;
IBOutlet UILabel *Lives;
IBOutlet UIImageView *Result;
}
-(IBAction)Answer1:(id)sender;
-(IBAction)Answer2:(id)sender;
-(IBAction)Answer3:(id)sender;
-(IBAction)Answer4:(id)sender;
-(void)Category1;
-(void)Category2;
-(void)Category3;
-(void)Category4;
-(void)Category5;
-(void)Category6;
-(void)RightAnswer;
-(void)WrongAnswer;
#end
1- I can't understand it, can you elaborate more ?
2- No it will work fine to whatever range you specify, but note that if you need to generate random number between 0 to 89 (0 and 89 are included) you need to make it arc4random() %90;
Related
For my Quiz app, i am creating 4 custom radio buttons for 4 answers by setting active and inactive images . When i select the button the state changing to active but when i press previous button the state going to inactive .
Code for creating Custom buttons
//answer 1
targetLabel = [[UILabel alloc] init];
CGSize labelSize = CGSizeMake(240, 9999);
CGSize theStringSize = [ans1 sizeWithFont:targetLabel.font constrainedToSize:labelSize lineBreakMode:targetLabel.lineBreakMode];
targetLabel.frame = CGRectMake(targetLabel0.frame.origin.x+40, targetLabel0.frame.size.height+40, theStringSize.width, theStringSize.height);
targetLabel.text = ans1;
[targetLabel setNumberOfLines:0];
targetLabel.backgroundColor=[UIColor clearColor];
[targetLabel sizeToFit];
[scroll addSubview:targetLabel];
// button 1
ans1btn = [[UIButton alloc] initWithFrame:CGRectMake(15,targetLabel.frame.origin.y-5,30,30)];
ans1btn.backgroundColor=[UIColor redColor];
[ans1btn setSelected:NO];
[ans1btn setBackgroundImage:[UIImage imageNamed:#"gray.png"]
forState:UIControlStateNormal];
[ans1btn setBackgroundImage:[UIImage imageNamed:#"green.png"]
forState:UIControlStateSelected];
ans1btn.adjustsImageWhenHighlighted=YES;
[ans1btn addTarget:self
action:#selector(checkboxSelected:)
forControlEvents:UIControlEventTouchUpInside];
ans1btn.tag=1;
[scroll addSubview:ans1btn];
Calling method
-(void)checkboxSelected:(id)sender
{
checkBoxSelected = TRUE;
[ans1btn setSelected:checkBoxSelected];
if(checkBoxSelected==TRUE)
{
checkBoxSelected1=FALSE;
[ans1btn1 setSelected:checkBoxSelected1];
[ans1btn2 setSelected:checkBoxSelected1];
[ans1btn3 setSelected:checkBoxSelected1];
checkBoxSelected=TRUE;
targetLabel.textColor=[UIColor blackColor];
targetLabel1.textColor=[UIColor grayColor];
targetLabel2.textColor=[UIColor grayColor];
targetLabel3.textColor=[UIColor grayColor];
}
else
{
NSLog(#"the button is not selected");
}
}
Like that i am calling other button actions also
Can anyone please help me.
Thanks in advance.
There is no actual radio button in iOS but you can use the following code to do what you want,
First, second, third and fourthButtonTags are values those already have been set in .xib or .m file. Specific numbers are also can be used.
In your .h file;
#property (strong, nonatomic) UIButton *firstButton, *secondButton, *thirdButton, *fourthButton;
In your .m file;
- (IBAction)buttonSelection:(id)sender {
UIButton *senderButton = (UIButton *) sender;
if (senderButton.tag == firstButtonTag) {
if (_firstButton.selected) {
_firstButton.selected = NO;
}
else {
_firstButton.selected = YES;
_secondButton.selected = NO;
_thirdButton.selected = NO;
_fourthButton.selected = NO;
}
}
else if (senderButton.tag == secondButtonTag) {
if (_secondButton.selected) {
_secondButton.selected = NO;
}
else {
_secondButton.selected = YES;
_firstButton.selected = NO;
_thirdButton.selected = NO;
_fourthButton.selected = NO;
}
}
else if (senderButton.tag == thirdButtonTag) {
if (_thirdButton.selected) {
_thirdButton.selected = NO;
}
else {
_thirdButton.selected = YES;
_firstButton.selected = NO;
_secondButton.selected = NO;
_fourthButton.selected = NO;
}
}
else if (senderButton.tag == fourthButtonTag) {
if (_fourthButton.selected) {
_fourthButton.selected = NO;
}
else {
_fourthButton.selected = YES;
_firstButton.selected = NO;
_secondButton.selected = NO;
_thirdButton.selected = NO;
}
}
}
try like this ,here define one button globally and play with that button,no need to take tag and all other stuff
#property(nonatomic,retain)UIButton *previousSelectedBtn;
- (IBAction)radioButtonSelection:(UIButton *)sender {
sender.selected=YES;
if(_previousSelectedBtn)
_previousSelectedBtn.selected=NO;
_previousSelectedBtn=sender;
}
I would like to know how to correctly operate with two views by UISegmentController.
Now I have two UIViews and UISegmentController and procedure changeView:
- (void)changeView:(NSInteger)index {
switch (index) {
case 0:
self.recipeInfoView.alpha = 1;
self.recipeInfoView2.alpha = 0;
break;
case 1:
self.recipeInfoView.alpha = 0;
self.recipeInfoView2.alpha = 1;
break;
default:
break;
}
This code works, but each view have the same position and size and very uncomfortable to work with it.
I'm using storyboards.
First write following code For create UISegmentedControl and give color of your UIView.
- (void)viewDidLoad
{
[super viewDidLoad];
//Make hide of your UIView
self.recipeInfoView.hide = YES;
self.recipeInfoView2.hide = YES;
//Give color of your UIView
self.recipeInfoView.backgroundColor = [UIColor redColor];
self.recipeInfoView.backgroundColor = [UIColor blackColor];
//Create UISegmentedControl Controller
NSArray *itemArray = [NSArray arrayWithObjects: #"FirstView", #"SecondView", nil];
self.segmentedControl= [[UISegmentedControl alloc] initWithItems:itemArray];
self.segmentedControl.frame = CGRectMake(35, 100, 250, 33);
self.segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
self.segmentedControl.momentary=NO;
self.segmentedControl.tintColor=[UIColor darkGrayColor];
[self.segmentedControl addTarget:self action:#selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:self.segmentedControl];
}
// segmentAction Methods
- (IBAction)segmentAction:(id)sender
{
if([sender selectedSegmentIndex] == 0)
{
if(self.recipeInfoView.isHidden == YES)
self.recipeInfoView.Hidden == NO;
else
self.recipeInfoView.Hidden == NO;
if(self.recipeInfoView2.isHidden == YES)
self.recipeInfoView2.Hidden == YES;
else
self.recipeInfoView2.Hidden == YES;
}
else if([sender selectedSegmentIndex] == 1)
{
if(self.recipeInfoView2.isHidden == YES)
self.recipeInfoView2.Hidden == NO;
else
self.recipeInfoView2.Hidden == NO;
if(self.recipeInfoView.isHidden == YES)
self.recipeInfoView.Hidden == YES;
else
self.recipeInfoView.Hidden == YES;
}
}
set view property hidden = YES or NO instead of setting alpha for view
I have an iphone app that displays images and plays audio selected from a main menu.
The user clicks on a button to select the image/audio combo they want. The code to switch the views with animation works fine.
All of the code to display the image, play, pause, scrub, and stop the audio while in the new view works fine too.
However, when the users clicks the Main Menu button I want the playing audio to stop. I am using viewWillDisappear:(BOOL)animated to call the stop method:
-(void)viewWillDisappear:(BOOL)animated {
audioPlayer.stop;
[super viewWillDisappear: animated];}
This code doesn't stop the sound when the user switches back to the main menu view. Is there a better way to do this? Am I doing something wrong?
Here is the code from the entire class where the snippet above resides:
#import "twelthPoem.h"
UIImageView *largeImageView;
#implementation twelthPoem
-(void)resetControls
{
audioPlayer.currentTime = 0;
scrubber.value = 0;
[playButton setImage:[UIImage imageNamed:#"play_HL.png"]
forState:UIControlStateNormal];
}
-(void)play:(id)sender {
if (! audioPlayer.playing) {
audioPlayer.play;
[playButton setImage:[UIImage imageNamed:#"pauseHL.png"] forState:UIControlStateNormal];
}
else {
audioPlayer.pause;
[playButton setImage:[UIImage imageNamed:#"play_HL.png"] forState:UIControlStateNormal];
}
[self becomeFirstResponder];
}
-(void)stop:(id)sender {
audioPlayer.stop;
[self resetControls];
}
-(void)changeVolume:(id)sender {
audioPlayer.volume = volume.value;
[self becomeFirstResponder];
}
-(void)scrub:(id)sender {
if (audioPlayer.playing) {
audioPlayer.pause;
audioPlayer.currentTime = scrubber.value;
audioPlayer.play;
}
else
audioPlayer.currentTime = scrubber.value;
[self becomeFirstResponder];
}
-(void)createControls {
//play/pause button
playButton = [UIButton buttonWithType:UIButtonTypeCustom];
[playButton setFrame:CGRectMake(60,405,80,20)];
[playButton setImage:[UIImage imageNamed:#"play_HL.png"] forState:UIControlStateNormal];
[playButton addTarget:self action:#selector(play:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:playButton];
//stop button
stopButton = [UIButton buttonWithType:UIButtonTypeCustom];
[stopButton setFrame:CGRectMake(180,405,80,20)];
[stopButton setImage:[UIImage imageNamed:#"stopHL.png"] forState:UIControlStateNormal];
[stopButton addTarget:self action:#selector(stop:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:stopButton];
//volume control
volume = [[UISlider alloc] initWithFrame:CGRectMake(10,445,145,20)];
[volume addTarget:self action:#selector(changeVolume:)
forControlEvents:UIControlEventValueChanged];
volume.minimumValue = 0.0;
volume.maximumValue = 1.0;
volume.value = audioPlayer.volume;
volume.continuous = YES;
[self.view addSubview:volume];
//scrubber control
scrubber = [[UISlider alloc] initWithFrame:CGRectMake(165,445,145,20)];
[scrubber addTarget:self action:#selector(scrub:)
forControlEvents:UIControlEventValueChanged];
scrubber.minimumValue = 0.0;
scrubber.maximumValue = audioPlayer.duration;
scrubber.value = audioPlayer.currentTime;
scrubber.continuous = NO;
[self.view addSubview:scrubber];
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
switch (event.subtype)
{
case UIEventSubtypeRemoteControlTogglePlayPause:
[self play:nil];
break;
case UIEventSubtypeRemoteControlNextTrack:
//do nothing
break;
case UIEventSubtypeRemoteControlPreviousTrack:
//do nothing
break;
}
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
-(void)viewDidLoad {
//for scrolling the image
[super viewDidLoad];
CGRect scrollFrame = CGRectMake(0,40,320,350);
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:scrollFrame];
scrollView.minimumZoomScale = 1.0;
scrollView.maximumZoomScale = 1.5;
scrollView.delegate = self;
UIImage *bigImage = [UIImage imageNamed:#"birches.png"];
largeImageView = [[UIImageView alloc] initWithImage:bigImage];
[scrollView addSubview:largeImageView];
scrollView.contentSize = largeImageView.frame.size; //important!
[self.view addSubview:scrollView];
[scrollView release];
//for playing the recording
NSString *filePath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:#"birches_final_mp3.mp3"];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSError *error = nil;
OSStatus status = AudioSessionInitialize(NULL, NULL, NULL, NULL);
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
status = AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,
sizeof (sessionCategory),
&sessionCategory);
AudioSessionSetActive(YES);
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL
error:&error];
if (error )
NSLog(#"An error occurred: %#",error);
else
{
audioPlayer.volume = 0.3;
[audioPlayer prepareToPlay];
[self createControls];
}
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return largeImageView;
}
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player
{
interrupted = audioPlayer.playing;
}
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player
{
if (interrupted)
audioPlayer.play;
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player
successfully:(BOOL)flag
{
[self resetControls];
}
-(void)viewWillDisappear:(BOOL)animated {
audioPlayer.stop;
[super viewWillDisappear: animated];
}
- (void)dealloc {
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[scrubber release];
[volume release];
[audioPlayer release];
[super dealloc];
}
#end
You call methods in objective-c using the following syntax.
[audioPlayer stop];
audioPlayer.stop will not work.
Same goes for other places as well.
audioPlayer.stop will not work mostly because it needs an expression after it, e.g. audioPlayer.stop = //expression, stop is a bool, so you can say audioPlayer.stop = YES; or [audioPlayer stop];
Hi i have a question here,
i'm able to get the UrL string store in "imageName" variable successfully in showImage method.
I need to do the same in this method "segmentedControlIndexChanged" but i cant get the variable "imageName".
Is there anyway i can declare the IBAction method to work similarly as the showImage method?
I Tried ->" -(IBAction) segmentedControlIndexChanged:(NSString *)imageName{} " but it cant work, i'm unable to get the variable "imageName".
- (void) showImage:(NSString *)imageName
{
NSData *imageData;
//NSString * string1 = [NSString stringWithFormat:imageName];
imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageName]];
//NSLog(#"%#",imageName);
image = [[UIImage alloc] initWithData:imageData];
self.imageView.image = image;
[imageView setFrame:CGRectMake(5, 10, image.size.width, image.size.height)];
[scrollview setScrollEnabled:YES];
if(image.size.height+20 >= 224)
{
[scrollview setContentSize:CGSizeMake(289, image.size.height + 20)];
}
else {
[scrollview setContentSize:CGSizeMake(289, 224)];
}
}
////////
-(IBAction) segmentedControlIndexChanged{
switch (self.segmentedControl.selectedSegmentIndex) {
case 0:
image = [UIImage imageNamed:image1name];
self.imageView.image = image;
[imageView setFrame:CGRectMake(5, 10, image.size.width, image.size.height)];
[scrollview setScrollEnabled:YES];
if(image.size.height+20 >= 224)
{
[scrollview setContentSize:CGSizeMake(289, image.size.height + 20)];
}
else {
[scrollview setContentSize:CGSizeMake(289, 224)];
}
break;
case 1:
image = [UIImage imageNamed:image2name];
self.imageView.image = image;
[imageView setFrame:CGRectMake(5, 10, image.size.width, image.size.height)];
[scrollview setScrollEnabled:YES];
[scrollview setContentSize:CGSizeMake(289, image.size.height+20)];
break;
case 2:
image = [UIImage imageNamed:image3name];
self.imageView.image = image;
[imageView setFrame:CGRectMake(5, 10, image.size.width, image.size.height+1)];
[scrollview setScrollEnabled:YES];
[scrollview setContentSize:CGSizeMake(289, image.size.height+20)];
break;
default:
break;
}
}
EDIT
I have encountered Bad Access error, anyone knows what does it mean or can anyone show me some ways to solve it?
No, an IBAction can only have one of the following three signatures in iOS:
- (void)action
- (void)action:(id)sender
- (void)action:(id)sender forEvent:(UIEvent *)event
EDIT
You could extend UIButton to store the value you need, like:
#interface MyButton : UIButton {
}
#property (nonatomic, retain) NSString *url;
#end
...
#implementation MyButton
#synthesize url;
#end
...
- (void)buttonTapped:(id)sender {
MyButton *button = (MyButton *)sender;
UIImage *image = [UIImage imageNamed:button.url];
...
}
EDIT
You can use tags to differentiate between different senders, like
enum {
ButtonOneTag = 128,
ButtonTwoTag,
...
}
...
- (void)buttonTapped:(id)sender {
UIButton *button = (UIButton *)sender;
switch(button.tag) {
case ButtonOneTag:
NSLog(#"Button One Tapped");
break;
case ButtonTwoTag:
NSLog(#"Button Two Tapped");
break;
}
You can also just compare the sender to ivars for the buttons like so:
- (void)buttonTapped:(id)sender {
//assuming buttonOne and buttonTwo are IBOutlets on this class
if (sender == self.buttonOne) {
NSLog(#"Button One Tapped");
else if (sender == self.buttonTwo) {
NSLog(#"Button Two Tapped");
}
...
}
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.
}