buttons check the correct answer objective-c - 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...
}
}

Related

remove objects from array based on the index

I have array of images here i am doing check and uncheck the images finally i have delete button which are the images i check i need to remove the images from array based on the button selection
here is my code
- (IBAction)delete_btn_touch:(id)sender {
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
for(int i=0; i<_GalleryimageArry.count;i++){
_imageV = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.view.frame) * i/2*0.6, 0, 100, 100)];
self.Crossbtn =[[UIButton alloc]initWithFrame:CGRectMake(_imageV.image.size.width/2+80,0,20,20)];
UIImage *btnImage = [UIImage imageNamed:#"unselectimag"];
[self.Crossbtn setImage:btnImage forState:UIControlStateNormal];
_imageV.contentMode = UIViewContentModeScaleAspectFill;
_imageV.image = [_GalleryimageArry objectAtIndex:i];
[_imageV setUserInteractionEnabled:YES];
_imageV.tag = i;
self.Crossbtn.tag =i;
[self.Crossbtn addTarget:self action:#selector(deleteImage:) forControlEvents:UIControlEventTouchUpInside];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(imageTapMethod:)];
[_imageV addGestureRecognizer:tap];
[self.imageV addSubview:self.Crossbtn];
[self.imageGalleryscroll addSubview:_imageV];
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}
self.imageGalleryscroll.delegate = self;
index=0;
self.imageGalleryscroll.contentSize = CGSizeMake(CGRectGetWidth(self.view.frame) * _GalleryimageArry.count/2*0.7, CGRectGetHeight(self.imageGalleryscroll.frame));
[self.imageGalleryscroll setPagingEnabled:YES];
[self.imageGalleryscroll setShowsHorizontalScrollIndicator:NO];
self.imageGalleryscroll.alwaysBounceVertical = NO;
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
-(void)deleteImage:(UIButton *)sender{
btn = (UIButton *)sender;
self.add_delete_view.hidden =YES;
self.deleteview.hidden=NO;
if( [[btn imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:#"unselectimag"]])
{
[btn setImage:[UIImage imageNamed:#"Crossimg"] forState:UIControlStateNormal];
[btn setSelected:YES];
[btn setTag:index];
}
else
{
[btn setImage:[UIImage imageNamed:#"unselectimag"] forState:UIControlStateNormal];
// other statements
self.selectedimages =#"No";
image = [self.GalleryimageArry objectAtIndex:index];
[self.GalleryimageArry addObject:image];
}
NSLog(#"%#", self.GalleryimageArry);
}
- (IBAction)delete_all_img_btn_touch:(id)sender {
// self.view (change it with your button superview)
if (btn.selected) {
[self.GalleryimageArry removeObjectAtIndex:index];
}
//here i need to removeObjectAtIndex:index based on the how many button are selected
}
any one help me to solve this issues
thanks in advance
Use the following code, where you want to clear the back stack of controllers.
-(void)clearStack
{
NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];
[navigationArray removeAllObjects];
//[navigationArray removeObjectAtIndex: 2];
self.navigationController.viewControllers = navigationArray;
}

In Objective-C, how can I make this code efficient?

[self.menuBtn1 setImage:[UIImage imageNamed:#"menu1.png"] forState:UIControlStateNormal];
[self.menuBtn2 setImage:[UIImage imageNamed:#"menu2.png"] forState:UIControlStateNormal];
[self.menuBtn3 setImage:[UIImage imageNamed:#"menu3.png"] forState:UIControlStateNormal];
[self.menuBtn4 setImage:[UIImage imageNamed:#"menu4.png"] forState:UIControlStateNormal];
[self.menuBtn5 setImage:[UIImage imageNamed:#"menu5.png"] forState:UIControlStateNormal];
[self.menuBtn6 setImage:[UIImage imageNamed:#"menu6.png"] forState:UIControlStateNormal];
[self.menuBtn7 setImage:[UIImage imageNamed:#"menu7.png"] forState:UIControlStateNormal];
This Code is very inefficient. But I think it can be efficient with forsyntax. However I don't know how can I code self.menuBtn%d with for. In Objective-C, How can I code this?
This access the button properties dynamically so you don't need an array. This only works if the buttons have already been initialized (they are if they're IBOutlets)
NSString *imageName;
NSString *buttonName;
UIImage *image;
for (int i = 1; i < 8; i++) {
//#autoreleasepool {
imageName = [NSString stringWithFormat:#"menu%d", i];
buttonName = [NSString stringWithFormat:#"menuBtn%d", i];
image = [UIImage imageNamed:imageName];
UIButton *button = (UIButton *)[self valueForKey:buttonName];
if (button)
[button setImage:image forState:UIControlStateNormal];
/*
If you needed to scale this to say 1000 images, you can uncomment the first
and last line in the for-loop which will automatically release the variables
each iteration so the memory consumption doesn't spike.
*/
//}
}
One solution might be to set the tag of all your buttons to some value (e.g. 100 + button number), then to try:
for (UIButton *aButton in self.view.subviews)
{
if ((aButton.tag >= 100 and aButton.tag < 107))
[aButton setImage:[UIImage imageNamed:[NSString stringWithFormat:#"menu%d.png",aButton.tag]] forState:UIControlStateNormal];
}
First add the buttons to the array and the use for loop like this:
NSArray *array=[NSArray arrayWithObjects:menuBtn1,menuBtn2,menuBtn3,menuBtn4,menuBtn5,menuBtn6menuBtn7,nil];
int i=1;
for(UIButton *aButton in array){
[aButton setImage:[UIImage imageNamed:[NSString stringWithFormat:#"menu%d.png",i++]] forState:UIControlStateNormal];
}
NSString *menubutton;
NSMutableArray *imagearray = [[NSMutableArray alloc]initWithObjects:#"image1.png",#"image2.png",#"image3.png", nil];
for(int i=0; i<[imagearray count]; i++)
{
menubutton = [NSString stringWithFormat:#"menuBtn%d",i];
UIButton *button = (UIButton *)[self valueForKey:menubutton];
[button setImage:[UIImage imageNamed:[NSString stringWithFormat:#"%#",[imagearray objectAtIndex:i]]] forState:UIControlStateNormal];
}

UIButton title replacement with each press

I would like to present to the user with each press of the button different letter from the ABC.
So when it first click on the application the user will see the letter A, then they will need to press the button and then they will see the letter B and so forth.
My challenge is how to replace the text of the title with each click on the button.
I wrote down some code, of two functions, if you will take a closer look you will see that -(void)displayABC:(id)sender is getting called each time so each time I getting the first member of the array, so first time the user see the letter A then it press on the button and she/he see the letter B which is the first member of the array, but each the same letter is been presented because each time, we loading the plist file and therefore we keep calling the first member of the array.
Any ideas how to solve it?
-(void)createLoginBioButton
{
authButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[authButton setBounds:CGRectMake(300,300, 150, 150)];
[authButton setCenter:CGPointMake(150, 240)];
[self.view addSubview:authButton];
[authButton setEnabled:true];
[authButton setTitle:#"A" forState:UIControlStateNormal];
[authButton setFont:[UIFont systemFontOfSize:70]];
[authButton addTarget:self
action:#selector(displayABC:)
forControlEvents:UIControlEventAllTouchEvents];
}
-(void)displayABC:(id)sender
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"ABC" ofType:#"plist"];
NSArray *ABCArray = [NSArray arrayWithContentsOfFile:path];
for (NSString *ABCValues in ABCArray){
[authButton setTitle:ABCValues forState:UIControlStateNormal];
}
}
Why not keep a reference to the current letter index as an instance variable and increment that with each touch?
Psuedo code
#property NSArray *abcs;
#property int currentIndex;
- (void)viewDidLoad {
[super viewDidLoad];
self.abcs = //load it from the plist
[self updateButtonText];
}
- (void)buttonTouched
{
self.currentIndex++;
if ( self.currentIndex >= self.abcs.count ) {
self.currentIndex = 0;
}
[self updateButtonText];
}
- (void)updateButtonText
{
[self.button setTitle:self.abcs[self.currentIndex] forControlState:UIControlStateNormal];
}
Simplest solution would be to put a static variable which keeps tracking index
-(void)createLoginBioButton
{
authButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[authButton setBounds:CGRectMake(300,300, 150, 150)];
[authButton setCenter:CGPointMake(150, 240)];
[self.view addSubview:authButton];
[authButton setEnabled:true];
[authButton setTitle:#"A" forState:UIControlStateNormal];
[authButton setFont:[UIFont systemFontOfSize:70]];
[authButton addTarget:self action:#selector(displayABC:) forControlEvents:UIControlEventAllTouchEvents];
}
-(void)displayABC:(id)sender
{
static int index = 0;
NSString *path = [[NSBundle mainBundle] pathForResource:#"ABC" ofType:#"plist"];
NSArray *ABCArray = [NSArray arrayWithContentsOfFile:path];
if(index < [ABCArray count])
[authButton setTitle:[ABCArray objectAtIndex:index] forState:UIControlStateNormal];
index++;
}

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

Passing an object to selector action

Ok simple question but can't find an answer.
I'v got a button to save information in my app.
I have
NSMutableArray *textFields = [[NSMutableArray alloc] initWithCapacity:5];
UITextField *textField = nil;
This is the information i want to save, i'v got 5 textfields in textFields mutablearray.
[save addTarget:self action:#selector(saveInfo)
forControlEvents:UIControlEventTouchUpInside];
and
-(void)saveInfo {
[[[NSUserDefaults standardUserDefaults] setValue: ????? forKey:#"Phone"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
The question is how to access and get information from like textFields[1].text in my saveInfo void ?
Ok To get things a little bit clearer i'v added the whole class. its not very big, and maybe someone could see thats the problem with my implementation .
#implementation Settings
- (id)init: (TableViewController*) TableControll {
NSMutableArray *textFields = [[NSMutableArray alloc] initWithCapacity:5];
UITextField *textField = nil;
for (int i = 0; i < 3; i++) {
textField = [[UITextField alloc] initWithFrame:CGRectMake(0.0f, 0.0f+(i*35), 120.0f, 30.0f)];
textField.backgroundColor = [UIColor whiteColor];
[textField setBorderStyle:(UITextBorderStyleRoundedRect)];
[TableControll.view addSubview:textField];
[textFields addObject:textField];
[textField release]; textField = nil;
}
UITextField *textName = textFields[0];
textName.placeholder = #"Vardas";
UITextField *textNo = textFields[1];
textNo.placeholder = #"Telefonas";
textNo.keyboardType = UIKeyboardTypeNumberPad;
UITextField *textPin = textFields[2];
textPin.keyboardType = UIKeyboardTypeNumberPad;
textPin.placeholder = #"Pin";
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(150, 20, 160, 30);
[button setTitle:#"Advanced settings" forState:UIControlStateNormal];
[TableControll.view addSubview:button];
UIButton *save = [UIButton buttonWithType:UIButtonTypeRoundedRect];
save.frame = CGRectMake(150, 60, 160, 30);
[save setTitle:#"Save settings" forState:UIControlStateNormal];
[TableControll.view addSubview:save];
[button addTarget:self action:#selector(goAdvanced)
forControlEvents:UIControlEventTouchUpInside];
[save addTarget:self action:#selector(saveInfo)
forControlEvents:UIControlEventTouchUpInside];
return self;
}
-(void)goAdvanced {
AppDelegate *newControll = (AppDelegate*)[UIApplication sharedApplication].delegate;
[newControll ChangeController];
}
-(void)saveInfo {
for(int i=0;i<5;i++) {
UITextField *tempTxtField=[_textFields objectAtIndex:i];
NSLog(#"do it %#",tempTxtField.text);
}
}
#end
What you'd want to do if you are using interface builder is create a bunch of IBOutlet for your textfields instead of keeping them in an array. Check out this: tutorial
Now it looks like you're creating things by hand, so in this case, you probably just want to declare your array as #property so it can be accessed by your save method.
To access the text property of a UITextField from your array you would write:
((UITextField *)[textFields objectAtIndex:1]).text
If you want to access the all textfield,
for(int i=0;i<[textFields count];i++) {
UITextField *tempTxtField=[textFields objectAtIndex:i];
NSlog(#"%#",tempTxtField);
}
-(void)saveInfo {
NSMutableArray *tempArr = [NSMutableArray array];
for(int i = 0; i < [textFieldsArray count]; i++){
[tempArr addObject:[(UITextField*)[textFieldsArray objectAtIndex:i]text]];
}
[[[NSUserDefaults standardUserDefaults] setValue:tempArr forKey:#"Phone"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
I'm not entirely sure I understand your question, but this is what I would do in your place. Instead of creating an array to hold each of the textfields, I'd just assign them a custom tag. Any number will work (although avoid zero since that's the default tag on all views). So your init method would look like this:
for (int i = 0; i < 3; i++) {
textField = [[UITextField alloc] initWithFrame:CGRectMake(0.0f, 0.0f+(i*35), 120.0f, 30.0f)];
textField.backgroundColor = [UIColor whiteColor];
textField.tag = (i+1);
[textField setBorderStyle:(UITextBorderStyleRoundedRect)];
[TableControll.view addSubview:textField];
[textField release]; textField = nil;
}
Then in the code that you want to reference the text field, you'd retrieve the view by its tag, making sure to cast it as UITextField.
-(void)saveInfo {
for(int i=0;i<5;i++) {
UITextField *textField = nil;
UIView *view = [self.view viewsWithTag:i];
if ([view isKindOfClass:[UITextField class]]) {
textField = (UITextField *) view;
NSLog(#"do it %#",textField.text)
}
}
}
NOTE: I'm referencing self.view but you'll need to reference TableControll.view. You'll need to retain a reference to it somewhere in your code. Also, I'd recommend your start using ARC.
Hope that helps! Good luck!