check answer and remove UIButton (Objective-C) - objective-c

I have a series of questions and answers that it's loads randomly,each question have 3 choice, in one of my question I have just true and false,
my questions is how can I set my if statement, That if my answer is true or false don't show the last buttons,
Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSString *qOne = #"Question 1";
NSString *qTwo = #"Question 2";
NSString *qThree = #"Question 3";
NSString *qFour = #"Question 4";
NSString *answerOne = #"Après le souper";
NSString *answerTwo = #"1";
NSString *answerThree = #" Holstein";
NSString *answerFour = #" yes";
NSString *answer2One = #"Après un exercice physique";
NSString *answer2Two = #" 2";
NSString *answer2Three = #" Jersey";
NSString *answer2Four = #" No";
NSString *answer3One = #"Avant un exercice physique";
NSString *answer3Two = #" 4";
NSString *answer3Three = #" Canadienne";
I want to remove this part
NSString *answer3Four = #" ";
NSString *correctOne = #"Après un exercice physique";
NSString *correctTwo = #" 4";
NSString *correctThree = #" Yes";
NSString *correctFour = #" 14";
answerComments = [[NSArray alloc] initWithObjects: answerOne, answerTwo, answerThree, answerFour, nil];
answer2Comments = [[NSArray alloc] initWithObjects: answer2One, answer2Two, answer2Three, answer2Four, nil];
answer3Comments = [[NSArray alloc] initWithObjects: answer3One, answer3Two, answer3Three, answer3Four,nil];
qComments = [[NSArray alloc] initWithObjects:qOne, qTwo, qThree, qFour, nil];
correctComments = [[NSArray alloc] initWithObjects: correctOne, correctTwo, correctThree, correctFour, nil];
// A random string is selected and assigned to artist.
int rand = arc4random()%4;
NSString *artist = [qComments objectAtIndex:rand];
firstAnswer = [answerComments objectAtIndex:rand];
secondAnswer = [answer2Comments objectAtIndex:rand];
threeAnswer = [answer3Comments objectAtIndex:rand];
correct = [correctComments objectAtIndex:rand];
NSLog (#"%#",correct);
// Here's the problematic code:
[question setText:(artist)];
[question setFont:[UIFont fontWithName:#"HelveticaRoundedLTStd-Bd" size:42]];
question.adjustsFontSizeToFitWidth = NO;
question.numberOfLines = 0;
[test setTitle:(firstAnswer) forState:UIControlStateNormal];
[test setBackgroundImage:[UIImage imageNamed:#"activeBtn.png"] forState:UIControlStateHighlighted];
[ansONE setTitle:(secondAnswer) forState:UIControlStateNormal];
[ansONE setBackgroundImage:[UIImage imageNamed:#"activeBtn.png"] forState:UIControlStateHighlighted];
ansTWO = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[ansTWO addTarget:self
action:#selector(ansTWO:)
forControlEvents:UIControlEventTouchDown];
[ansTWO setTitle:(threeAnswer) forState:UIControlStateNormal];
[ansTWO setBackgroundImage:[UIImage imageNamed:#"activeBtn.png"] forState:UIControlStateHighlighted];
ansTWO.titleLabel.font = [UIFont fontWithName:#"HelveticaRoundedLTStd-Bd" size:24];
[ansTWO setTitleColor:[UIColor colorWithRed:21/255.0 green:119/255.0 blue:183/255.0 alpha:.77] forState:UIControlStateNormal];
ansTWO.titleLabel.textAlignment = UITextAlignmentCenter;
[ansTWO setTag:2];
UIImage *buttonImage = [UIImage imageNamed:#"quizBtn.png"];
[ansTWO setBackgroundImage:buttonImage forState:UIControlStateNormal];
ansTWO.frame = CGRectMake(243, 586,549, 56);
[self.view addSubview:ansTWO];
}

Assuming that you know how to interpret the answer to be TRUE or FALSE you can have some if statement like this:
//1st Option
if(answer){
button.hidden = YES;
//hide or unhide other buttons
}
//2 Option
if(answer){
[button removeFromSuperView];
//add or remove other buttons
}

Related

objective-c : only last value iterated in for-each loop is displayed in the label

Name count i get after parsing json is random i.e. it can display any number of values ranging from 1 to 100. I created that many number of labels as shown in the code below, but only the last iterated value is displayed in the label when i pass NSString *name to putLabelsInScrollView method. Can any one help me out to fix this logic to display different name in different created labels? I cannot create tableview which would have been easy and will rectify the cGRects of label and textfields later.
int i = 0;
for(NSDictionary *myJsonDictionary in myJsonArray)
{
//UILabel *label = (UILabel *)[arrayLabel objectAtIndex:i++];
//[label setText:myJsonDictionary[#"Name"]];
NSUserDefaults *defaultNames = [NSUserDefaults standardUserDefaults];
NSString *name = myJsonDictionary[#"Name"];
[defaultNames setObject:name forKey:#"QUESTIONNAME"];
NSLog(#"Value is %# \n", name);
i++;
}
NSLog(#"Number of cycles in for-each = %d", i);
[self putLabelsInScrollView:i];
- (void) putLabelsInScrollView:(int)numberOfLables
{
for(int i = 0 ; i < numberOfLables ; i++)
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, yPosition_label, 261, 30)];
[label setFont:[UIFont fontWithName:#"Helvetica Neue" size:12.0f]];
label.numberOfLines = 2;
NSUserDefaults *defaultNameFetch = [NSUserDefaults standardUserDefaults];
NSString *fetchedString = [defaultNameFetch objectForKey:#"QUESTIONNAME"];
[label setText:[NSString stringWithFormat:#"%#", fetchedString]];
//[label setText:myJsonDictionary[#"Name"]];
[self.scroll addSubview:label];
yPosition_label += 80;
UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(10, yPosition_text, 261, 30)];
text.borderStyle = UITextBorderStyleRoundedRect;
text.textColor = [UIColor blackColor];
text.font = [UIFont systemFontOfSize:12.0];
text.backgroundColor = [UIColor clearColor];
text.keyboardType = UIKeyboardTypeDefault;
text.delegate = self;
[self.scroll addSubview:text];
yPosition_text += 100;
yPosition_result = yPosition_label + yPosition_text;
}
[self.scroll setContentSize:CGSizeMake(self.scroll.frame.size.width, yPosition_result)];
[self.view addSubview:self.scroll];
}
Just Try this...
for(NSDictionary *myJsonDictionary in myJsonArray)
{
NSString *name = myJsonDictionary[#"Name"];
[self putLabelsInScrollView:name];
NSLog(#"Value is %# \n", name);
}
[self.scroll setContentSize:CGSizeMake(self.scroll.frame.size.width, yPosition_result)];
[self.view addSubview:self.scroll];
- (void) putLabelsInScrollView:(NSString *)labelText
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, yPosition_label, 261, 30)];
[label setFont:[UIFont fontWithName:#"Helvetica Neue" size:12.0f]];
label.numberOfLines = 2;
[label setText:labelText];
//[label setText:myJsonDictionary[#"Name"]];
[self.scroll addSubview:label];
yPosition_label += 80;
UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(10, yPosition_text, 261, 30)];
text.borderStyle = UITextBorderStyleRoundedRect;
text.textColor = [UIColor blackColor];
text.font = [UIFont systemFontOfSize:12.0];
text.backgroundColor = [UIColor clearColor];
text.keyboardType = UIKeyboardTypeDefault;
text.delegate = self;
[self.scroll addSubview:text];
yPosition_text += 100;
yPosition_result = yPosition_label + yPosition_text;
}
Replace your code with this:
Fetching results:
int i = 0;
NSMutableArray *texts = [NSMutableArray array];
for(NSDictionary *myJsonDictionary in myJsonArray)
{
//UILabel *label = (UILabel *)[arrayLabel objectAtIndex:i++];
//[label setText:myJsonDictionary[#"Name"]];
NSUserDefaults *defaultNames = [NSUserDefaults standardUserDefaults];
NSString *name = myJsonDictionary[#"Name"];
[texts addObject:name];
NSLog(#"Value is %# \n", name);
i++;
}
NSLog(#"Number of cycles in for-each = %d", i);
[self putLabelsInScrollView:i withTexts:texts];
And method for putting labels' texts
- (void) putLabelsInScrollView:(int)numberOfLables withTexts:(NSArray *)texts
{
for(int i = 0 ; i < numberOfLables ; i++)
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, yPosition_label, 261, 30)];
[label setFont:[UIFont fontWithName:#"Helvetica Neue" size:12.0f]];
label.numberOfLines = 2;
NSUserDefaults *defaultNameFetch = [NSUserDefaults standardUserDefaults];
NSString *fetchedString = texts[i];
[label setText:fetchedString];
//[label setText:myJsonDictionary[#"Name"]];
[self.scroll addSubview:label];
yPosition_label += 80;
UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(10, yPosition_text, 261, 30)];
text.borderStyle = UITextBorderStyleRoundedRect;
text.textColor = [UIColor blackColor];
text.font = [UIFont systemFontOfSize:12.0];
text.backgroundColor = [UIColor clearColor];
text.keyboardType = UIKeyboardTypeDefault;
text.delegate = self;
[self.scroll addSubview:text];
yPosition_text += 100;
yPosition_result = yPosition_label + yPosition_text;
}
[self.scroll setContentSize:CGSizeMake(self.scroll.frame.size.width, yPosition_result)];
[self.view addSubview:self.scroll];
}

UIButtons in UIScrollView stop working after 3 rows

I have a UIScrollView with a list of UIViews within it. Bit like a fancy tableview. One issue I am having is the buttons work ok for the first 3 'rows' in the scrollview, but none of the buttons after this respond when i scroll down. Looks like its working ok for the buttons that show on screen when the view has loaded but anything further down when i scroll will now respond at all...
code from within the uiview repeated within uiscrollview
-(void)addButtons
{
UIButton *visiteWebSite = [UIButton buttonWithType:UIButtonTypeCustom];
[visiteWebSite addTarget:self
action:#selector(visitSite:)
forControlEvents:UIControlEventTouchDown];
[visiteWebSite setTintColor:[UIColor colorWithRed:247 green:143 blue:30 alpha:1.0]];
visiteWebSite.frame = CGRectMake(440.0, 10.0, 120.0, 26.0);
if(![self IsPhone5]) {
visiteWebSite.frame = CGRectMake(350.0, 10.0, 120.0, 26.0);
}
//visiteWebSite.backgroundColor = [UIColor orangeColor]; //[UIColor colorWithRed:247 green:143 blue:30 alpha:1.0];
[visiteWebSite setBackgroundImage:[UIImage imageNamed:#"orangeBG"] forState:UIControlStateNormal];
[visiteWebSite setTitle:#"VISITE WEBSITE" forState:UIControlStateNormal];
visiteWebSite.titleLabel.font = [UIFont fontWithName:#"arial" size:12];
[self addSubview:visiteWebSite];
UIButton *getDirections = [UIButton buttonWithType:UIButtonTypeCustom];
[getDirections addTarget:self
action:#selector(getDirections:)
forControlEvents:UIControlEventTouchDown];
[getDirections setTitle:#"GET DIRECTIONS" forState:UIControlStateNormal];
getDirections.titleLabel.font = [UIFont fontWithName:#"arial" size:12];
getDirections.frame = CGRectMake(440.0, 46.0, 120.0, 26.0);
if(![self IsPhone5]) {
getDirections.frame = CGRectMake(350.0, 46.0, 120.0, 26.0);
}
[getDirections setBackgroundImage:[UIImage imageNamed:#"orangeBG"] forState:UIControlStateNormal];
[self addSubview:getDirections];
}
Code from Parent View containing the UIScrollView
-(void)performSearch
{
[self.loadinglabel removeFromSuperview];
NSString* searchTerm = txtSearch.text;
searchTerm = [searchTerm stringByReplacingOccurrencesOfString:#" " withString:#""];
NSData *urldata = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.collectioncosmetics.co.uk/storelocatorapi?store=%#",searchTerm]]];
NSString *json = [[NSString alloc] initWithData:urldata encoding:NSUTF8StringEncoding];
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSArray *jsonObjects = [jsonParser objectWithString:json];
float y = 0;
float height = 84;
if([jsonObjects count] < 1) {
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:#"NO RESULTS" message:#"There are no stores near the postcode you searched" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alertView show];
[self back:nil];
return;
}
for (int i = 0; i < [jsonObjects count]; i++)
{
NSDictionary *dict = [jsonObjects objectAtIndex:i];
CARStoreResult* result = [[CARStoreResult alloc] initWithFrame:CGRectMake(0, height*i, tv.frame.size.width, height)];
result.name = [dict objectForKey:#"name"];
result.street = [dict objectForKey:#"street"];
result.area = [dict objectForKey:#"area"];
result.county = [dict objectForKey:#"County"];
result.postcode = [dict objectForKey:#"PostCode"];
result.distance = [dict objectForKey:#"distance"];
result.usersPostCode = searchTerm;
result.y = y;
result.num = i;
y = y + height;
[result build];
[tv addSubview:result];
}
[tv setFrame:CGRectMake(tv.frame.origin.x, tv.frame.origin.y, tv.frame.size.width, height*[jsonObjects count])];
[self.scrollView setContentSize:tv.frame.size];
[Flurry logEvent:#"Store Locator"];
}
FIXED!
instead of adding the views to a view within the scrollview i added them just directly to the scrollview. with the scrollview having scrollView.canCancelContentTouches set to NO.
//[tv addSubview:result];
[self.scrollView addSubview:result];
}
//[tv setFrame:CGRectMake(tv.frame.origin.x, tv.frame.origin.y, tv.frame.size.width, height*[jsonObjects count])];
[self.scrollView setContentSize:CGSizeMake(320, height*[jsonObjects count])];
//[self.scrollView setContentSize:tv.frame.size];
[Flurry logEvent:#"Store Locator"];

buttons check the correct answer objective-c

I have one UIViewController and inside I have NSArray that I put my correct answer,and also I have 3 buttons, and 3 NSArray for their titles, I want to check if my buttons title was equal to the correct answer then goes to the correct page else goes to the wrong page
would you please help me to this implementation:
Thanks in advance!
Here is my code:
NSString *correctOne = #"test1";
NSString *correctTwo = #"test2";
NSString *correctThree = #"test3";
NSString *correctFour = #"test4";
NSString *correctFive = #"test5";
NSString *correctSix = #"test6";
NSString *correctSeven = #"test7";
NSString *correctEight = #"test8";
correctComments = [[NSArray alloc] initWithObjects: correctOne, correctTwo, correctThree,
correctFour, correctFive, correctSix, correctSeven, correctEight, nil];
int rand = arc4random()%8;
NSString *correct = [correctComments objectAtIndex:rand];
[test setTitle:(firstAnswer) forState:UIControlStateNormal];
[test setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
[test setTag:0];
[ansONE setTitle:(secondAnswer) forState:UIControlStateNormal];
[ansONE setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
[ansONE setTag:1];
[ansTWO setTitle:(threeAnswer) forState:UIControlStateNormal];
[ansTWO setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
[ansTWO setTag:2];
- (IBAction)suivant:(id)sender {
//MY Question is how should I check my button title and correctComments
}
- (IBAction)suivant:(id)sender {
UIButton *button = (UIButton *)sender;
int correctIndex = ...;
BOOL thisIsTheCorrectButton = (button.tag == correctIndex);
// Do whatever
}
At first you have to store correct answer from your code snippet to a property:
self.correctAnswer = correct;
Then do the comparision of those strings:
- (IBAction)suivant:(UIButton *)sender {
// You wanted to check for title:
if ([sender.currentTitle isEqualToString:self.correctAnswer]) {
// Correct...
}
else {
// Wrong...
}
}

adding images on top of the button which is on a scrollview

NSData *data = [NSData dataWithContentsOfFile:#"path of XML"];
NSError *error = nil;
GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithData:data options:0 error:&error];
NSError *err=nil;
NSArray *nodes = [document nodesForXPath:#"/product_list/product[category = \"Pins & Collectibles\"]/image" error:&err];
NSMutableArray *array =[[NSMutableArray alloc]initWithCapacity:[nodes count]];
for(int i=0;i<[nodes count]; i++)
{
[array addObject:(NSString *)[[(NSString *)[[(NSString *)[[[NSString stringWithFormat:#"%#",[nodes objectAtIndex:i]] componentsSeparatedByString:#"{"] objectAtIndex:1] componentsSeparatedByString:#"<image>"] objectAtIndex:1] componentsSeparatedByString:#"</image>"] objectAtIndex:0] ];
}
NSLog(#"%#",array);
the array has all the images i need to put it on top of the button
This may work:
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setBackgroundImage:[UIImage imageWithData:IMAGE_DATA] forState:UIControlStateNormal];
Then make a for loop in that
for(int i=0;i<100;i++)
{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setBackgroundImage:[UIImage imageWithData:IMAGE_DATA] forState:UIControlStateNormal];
}

Image not stored in an NSMutableArray

i am trying to store image in NsMutable Array.But it not working in that function. But eventually in other function it work properly.can someone tell me why it is not working.
- (void)readPlistData {
objectButtonArray = [[NSMutableArray alloc] init]; \\Use to store Buttons
editButtonArray = [[NSMutableArray alloc] init]; \\ another array use to store deletebutton(such as.crossmark button.)
selectImage = [[NSMutableArray alloc] init];
self.myPlistPath = [NSString stringWithString:[self plistPath]];
plistArray = [[NSMutableArray alloc] initWithContentsOfFile:self.myPlistPath];
for (int i =0; i< [plistArray count];i++)
{
UIGraphicsEndImageContext();
NSData *imageData = [plistArray objectAtIndex:i];
currentObjectImage = [UIImage imageWithData:imageData] ;
[selectImage addObject:currentObjectImage]; \\value not stored in selectimage NSMutableArray
CGRect imageSize = CGRectMake(0, 0, 100, 90);
UIGraphicsBeginImageContext(imageSize.size); // this will crop
[currentObjectImage drawInRect:imageSize];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
imageButton = [[UIButton alloc]initWithFrame:CGRectMake(width, 0, 100, 90)];
[imageButton setTag:tag];
[imageButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[imageButton setImage:newImage forState:UIControlStateNormal];
CGRect backFrame = backView.frame;
backFrame.size.width = 120+width;
backView.frame = backFrame;
[backView addSubview:imageButton];
editButton = [[UIButton alloc]initWithFrame:CGRectMake(width-10, -10, 35, 35)];
[editButton setImage:[UIImage imageNamed:#"DeleteButton.png"] forState:UIControlStateNormal];
[editButton addTarget:self action:#selector(deleteObjectViewImage:) forControlEvents:UIControlEventTouchUpInside];
editButton.hidden = YES;
[editButton setTag:tag];
[backView addSubview:editButton];
tag++;
width = 120 + width;
[objectButtonArray addObject:imageButton];
[editButtonArray addObject:editButton];
}
scrollView.contentSize = backView.bounds.size;
}
can someone help me.
I think the problem is Reference name "currentObjectImage" basically when you are doing
[selectImage addObject:currentObjectImage];
it saves the reference of "currentObjectImage", where in the next iteration next image is loaded in it which creates problem.
Replace above line with
[selectImage addObject:[currentObjectImage copy]];
I think it will solve your problem.