UISegmentController and UIViews - iphone

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

Related

How to use exist label to show correct answer

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;

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

How to keep selection on radio buttons after clicking previous button

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;
}

Dynamic assignment of random images as button's background separately

-(void)setButtons_AsPerTheMatrixSelection
{
for(UIView *subview in [viewWithButtons subviews])
{
if ([subview isKindOfClass:[UIButton class]])
{
[subview removeFromSuperview];
}
}
viewWithButtons = [[UIView alloc] init];
width = 48;
height = 48;
pw = 49;
ph = 49;
arrButton = [[NSMutableArray alloc] init];
UIImage *imgDefaultBG = [UIImage imageNamed:#"bg.jpg"];
viewWithButtons.frame = CGRectMake(50, 40, 200, 260);
ch = 4;
cv = 4;
for ( i = 0 ; i < cv ; ++i )
{
for ( j = 0 ; j < ch ; ++j )
{
btnMatrix = [[[UIButton alloc] initWithFrame:CGRectMake(10+pw*j, 51+ph*i, width, height)] autorelease];
btnMatrix.tag = i*ch+j;
btnMatrix.userInteractionEnabled = TRUE;
bulImageStatus = FALSE;
[btnMatrix addTarget:self action:#selector(changeImage:) forControlEvents:UIControlEventTouchDown];
[btnMatrix setBackgroundImage:imgDefaultBG forState:UIControlStateNormal];
[viewWithButtons addSubview:btnMatrix];
[arrButton addObject:btnMatrix];
}
}
NSLog(#"arrButton object count is:--> %d",[arrButton count]);
[self.view addSubview:viewWithButtons];
}
-(void)AddImageToArray
{
arr_FirstSet = [[NSMutableArray alloc] init];
NSString *strImageName;
if(appDelegate.intCategoryBtnTag == 0)
{
for (intimg = 1; intimg <= 28; intimg++)
{
strImageName = [NSString stringWithFormat:#"%d_1.png",intimg];
NSLog(#"strImageName is :--> %#",strImageName);
[arr_FirstSet addObject:strImageName];
}
NSLog(#"arr_FirstSet objects are...%#",arr_FirstSet);
}
}
-(void)changeImage:(id)sender
{
UIImage *img;
NSString *strImageName;
strImageName = [arr_FirstSet objectAtIndex:arc4random() % [arr_FirstSet count]/2];
NSLog(#"btnMatrix is:--> %#",strImageName);
img = [UIImage imageNamed:strImageName];
//[btnMatrix setImage:img forState:UIControlEventTouchDown];
NSLog(#"sender detail is:--> %#",sender);
[sender setBackgroundImage:img forState:UIControlStateHighlighted];
}
This is my code to set the dynamic buttons in "setButtons_AsPerTheMatrixSelection" method,
"AddImageToArray" method is used to add images from bundle to NSMutableArray (arr_FirstSet) one by one.
"changeImage" method is used to set the background of particular button.
I am able to set the images as background to the buttons randomly,
But the main problem is that i have to set fixed dynamic image to particular button.
right now on each click of particular button i am getting changed random image when i press it once, twice, thrice etc...
I have to set any particular image which is generated randomly in the "changeImage" to single button & rest to the other buttons single-single.
Then i have to check if two buttons have same background then these two buttons will be removed from the matrix.
Please guide me for the mistake i am doing & help me.
//Please replace this method
-(void)changeImage:(UIButton *)sender
{
UIImage *img;
NSString *strImageName;
strImageName = [arr_FirstSet objectAtIndex:arc4random() % [arr_FirstSet count]/2];
img = [UIImage imageNamed:strImageName];
//for the first time sender.imageView.image property will be null then only we set image to the button.
//For second click this condition fails and does not set the other image.
if(!sender.imageView.image)
{
[sender setImage:img forState:UIControlStateHighlighted];
[sender setImage:img forState:UIControlStateSelected];
}
// Calling a method to check if two images of buttons are same.
[self checkIfTwoImagesAreSame:sender];
}
//And Add this method
- (void)checkIfTwoImagesAreSameImageMaching:(UIButton *)sender
{
for(UIView *subview in [viewWithButtons subviews])
{
if ([subview isKindOfClass:[UIButton class]])
{
UIButton *btn = (UIButton *)subview;
// This condition is comparing clicked button image with all the buttons images of the viewWithButtons view if it isEqual:
if(sender.imageView.image && btn.imageView.image && [sender.imageView.image isEqual:btn.imageView.image])
{
// this is checking if the clicked button is not comparing with itself
if(btn.tag != sender.tag)
{
[btn removeFromSuperview];
[sender removeFromSuperview];
// OR
// btn.selected = YES;
// sender.selected = YES;
// OR
// btn.hidden = YES;
// sender.hidden = YES;
}
}
}
}
}

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.
}