How to compare text from two labels in objective c - ios

I make a string split on two labels. label1 contain firstPart of string and label2 contain secondPart of string. Now i want to compare the text from two labels to make full string and show an alert of success when press on a button.See in this image blue label and gray label make full string "window" words labels
Here is my logic i perform in button press action but it always gives alert of try again,can any one please tell me where is my mistake in code.
get the text from file and store in an array and set label text.
label1.text = [arr1 objectAtIndex:i]; and [label2.text = arr2 objectAtIndex:i];
in button press method
- (IBAction)btnClicked:(id)sender
{
NSMutableArray *checkarry=[[NSMutableArray alloc]init];
for(int i=0;i<arr2.count;i++){
NSString *str=[NSString stringWithFormat:#"%#%#",[arr1 objectAtIndex:i],[arr2 objectAtIndex:i]];
[checkarry addObject:str];
}
NSSet *set1 = [NSSet setWithArray:arrayOfStringBeforeSpiliting];
NSSet *set2 = [NSSet setWithArray:checkarry];
if([set1 isEqualToSet:set2]){
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Success" message:#"Congarats" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
else{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Error" message:#"Try Again" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}

Related

Saving app data after iphone/ipad reset

The photo in the link below illustrates the app I am currently working on, the name is a UITextfield that the user edits him/herself and the balance is label in which the user clicks the add button to add their desired funds. Then the two textfields below that allow for the input of money spent and how it was spent, this is then saved as a UITableviewCell in the UITable view. The problem I am currently having right now is when I restart my iPhone device the previously inputted data is rested meaning the user will have to rewrite everything which wouldn't help as this is an app to monitor one's savings. I did some googling to see if there was a fix for this I came across NSUserDefaults and tried the following code in my viewDidLoad.
Could someone provide the steps for a different approach to keep the inputted information where it is even after the user turns off his or her iPhone/iPad etc. Heres the photo link
http://imgur.com/DceJ7gs
[[NSUserDefaults standardUserDefaults] synchronize];
This is the code I am using to add funds which in turn changes the balance displayed by the uilabel Balance in the above photo
- (IBAction)addFunds:(id)sender {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Add Funds" message:#"Please add your funds" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Done", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[_inputStatement resignFirstResponder];
[_spent resignFirstResponder];
[myTableView resignFirstResponder];
[_custName2 resignFirstResponder];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//alertview input text was blank so we are doing a check
if([[alertView textFieldAtIndex:0].text isEqual:#""] && buttonIndex == 1){
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Input Required" message:#"Please fill in the textfield" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
} else {
if(buttonIndex == 1){
NSString *tempText = [alertView textFieldAtIndex:0].text;
float toAdd = [tempText floatValue];
float add = [_currentBalance.text floatValue];
if(toAdd < 0) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"You can't add a negative number, try again" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
} else {
add = add + toAdd;
if(add >= 99999999.50){
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Well you broke it" message:#"You are not allowed to input this much. In the event you do have these funds, I apologize for putting in this restriction. Personally contact me at thejobemuhammed#gmail.com for further inquiries." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
} else {
_currentBalance.text = [NSString stringWithFormat:#"%.2f", add];
if(!array){
array = [[NSMutableArray alloc]init];
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
date1 = [NSDate dateWithTimeIntervalSinceNow:5];
NSString *resultString = [dateFormatter stringFromDate:date1];
[array insertObject:[NSString stringWithFormat:#"%#%#%#",#"$",tempText, #" deposited"] atIndex:0];
[date insertObject:resultString atIndex:0];
[details insertObject:#"This is a deposit" atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.myTableView insertRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
}
[_inputStatement resignFirstResponder];
[_spent resignFirstResponder];
[myTableView resignFirstResponder];
}
add this code where you want to save . i am not getting where are you saving .
save it using this code
NSString *valueToSave = #"hereis yourvalue";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:#"preferencekyename"];
[[NSUserDefaults standardUserDefaults] synchronize];
to get it back later using this code
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:#"preferencekyename"];

Unable to pass a variable into alert view

I have an array of names in 'names' . I am trying to display an alert when the user taps on a table cell. If the user touches the first cell then ,[names objectatindex:0] should be the message in the alert view. Here is what I have done
UIAlertView *okAlert = [[UIAlertView alloc] initWithTitle:#"ok" message:#"You have just tapped [names objectatindex:0]" delegate:self cancelButtonTitle:#"No" otherButtonTitles:#"Yes", nil];
okAlert.tag=0;
[okAlert performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
In the message it is not displaying the name. I couldn't figure out the problem. Could you please help me in this?
Thanks in advance.
Try this:
UIAlertView *okAlert = [[UIAlertView alloc] initWithTitle:#"OK"
message:[NSString stringWithFormat:#"You have just tapped %#.", [names objectAtIndex:0]]
delegate:self
cancelButtonTitle:#"No"
otherButtonTitles:#"Yes", nil];
message:#"You have just tapped [names objectatindex:0]"
You've hidden that code inside a string constant. Now it's just letters.
Try:
UIAlertView *okAlert = [[UIAlertView alloc] initWithTitle:#"ok"
message:[#"You have just tapped " stringByAppendingString:names.firstObject]
delegate:self cancelButtonTitle:#"No" otherButtonTitles:#"Yes", nil];

Checking to see if textfields are filled out

In my Calorie Tracker App, I have two textfields. One is for the name of the food, and the other is for the amount of calories.To check and see if they are filled I wrote the following code:
if([foodString isEqual: #" "])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning!" message:#"You have not entered the name of the meal!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
else if([self.amountText isEqual: #" "])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning!" message:#"You have not enteted the amount of calories!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
else if([self.amountText isEqual:#" "] && [foodString isEqual:#" "])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning!" message:#"You haven't entered anything!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
So for the one where the amountText textfield isn't filled out, but the nameOfFood is filled out, there is an alert. For the rest however, there is no alert. If anyone could provide the proper syntax for checking to see if my textfields are being filled out properly, it would be much appreciated.
Remember, my first textfield is a string value, and the other is an integer value.
Thanks in advance.

Check if UITextfield contains (? ! $ , etc)

Im doing a conditional statement that checks if a textfield contains certain characters, if it does they an UIAlertView will show. At the moment if the text field contains letters then an the alert is shown, how would I extend my method below to include characters such as ? ! , $ etc.
if ([self.withdrawTextField.text rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]].location != NSNotFound) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Ooops" message:#"Please only use numbers and the period (.)." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
Try this:
NSMutableCharacterSet *mcs1 = [[NSCharacterSet letterCharacterSet] mutableCopy];
[mcs1 addCharactersInString:#"?!.$"];
if ([self.withdrawTextField.text rangeOfCharacterFromSet:mcs1].location != NSNotFound) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Ooops" message:#"Please only use numbers and the period (.)." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
As you want only numbers and dot in the string than you can try below code. It may help you.
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789."];
for (int i = 0; i < [[self.withdrawTextField.text length]; i++)
{
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c])
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Ooops" message:#"Please only use numbers and the period (.)." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
}

How to create two textfields in an alert view, IOS

I want to create an alertview with two uitextfields inside of it.
method:
//show alertview for file input
- (IBAction)showAddFiles:(id)sender {
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Enter File Details"
message:nil
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Add", nil];
UITextField *textFieldDescription = [message textFieldAtIndex:0];
textFieldDescription.placeholder = #"File Description : Ex. Acat Briefing";
UITextField *textFieldFileName = [message textFieldAtIndex:1];
textFieldFileName.placeholder = #"Exact File Name : Ex. acat.pdf";
[message show];
}
//make sure file description is long enoguh
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
NSString *inputText = [[alertView textFieldAtIndex:0] text];
if( [inputText length] <= 15 && [inputText length] >= 4)
{
return YES;
}
else
{
return NO;
}
}
//handle add button
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Add"])
{
UITextField *fileDescription = [alertView textFieldAtIndex:0];
UITextField *fileName = [alertView textFieldAtIndex:1];
NSLog(#"Desc: %#\nName: %#", fileDescription.text, fileName.text);
}
}
Error:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'textFieldIndex (0) is outside of the bounds of the array of text fields'
Why I do get this error, how can I create two uitextfields in an alert view?
=========Working Solution ===========
Thanks for the answer below works when you only need two plain textfields
//show alertview for file input
- (IBAction)showAddFiles:(id)sender {
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Enter File Details"
message:nil
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Add", nil];
[message setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
UITextField *fileDescription = [message textFieldAtIndex:0];
fileDescription.placeholder=#"Ex. acat.pdf";
[[message textFieldAtIndex:1] setSecureTextEntry:NO];
UITextField *fileName= [message textFieldAtIndex:1];
fileName.placeholder=#"Ex. Acat Briefing";
[message show];
}
After you allocated the "message" alert view. Add this to your code:
[message setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
[[message textFieldAtIndex:1] setSecureTextEntry:NO];
This will make your alert view two text field inside.
The error you received occurs because there are no text fields in your UIAlertView, 'message'. The instance method "textFieldAtIndex" exists to access textFields in a UIAlertView that is created with a specific style, like UIAlertViewStylePlainTextInput, UIAlertViewStyleSecureTextInput, or UIAlertViewStyleLoginAndPasswordInput. These styles are set on the property "alertViewStyle". For example:
[message setAlertViewStyle:UIAlertViewStylePlainTextInput];
You may use "textFieldAtIndex" after setting this property, but unfortunately it looks as if none of these styles suit your needs.
What I've done before is to create a default styled UIAlertView (like you've already done), and add UITextFields as subviews to the UIAlertView.
For Example:
//Create the alert then add any labels and text fields as subviews.
//You can pad out an alertView by adding newline characters in the message. This will
// give the alertView more space to draw the text fields.
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Two Text Field Alert"
message:#"\n\n\n\n\n"
delegate:self
cancelButtonTitle:#"CanceL"
otherButtonTitles:#"OK", nil];
UITextField *textField1 = [[UITextField alloc] initWithFrame:CGRectMake(16,83,252,25)];
textField1.borderStyle = UITextBorderStyleRoundedRect;
textField1.keyboardAppearance = UIKeyboardAppearanceAlert;
textField1.delegate = self;
[message addSubview:textField1];
UITextField *textField2 = [[UITextField alloc] initWithFrame:CGRectMake(16,112,252,25)];
textField2.placeholder = #"Password";
textField2.borderStyle = UITextBorderStyleRoundedRect;
textField2.keyboardAppearance = UIKeyboardAppearanceAlert;
textField2.delegate = self;
[message addSubview:textField2];
[message show];
[message release];
[textField2 release];
[textField1 release];
It's a lot more verbose and messy to do a login this way as opposed to the alertView styles, but you can adapt this as you see fit to add any number of subviews to an alert view.
Edited to simplify example.
You're getting that error because the UIAlertView does not contain any textfields. Since the alert view's textfield collection is empty when you try to call [alertView textFieldAtIndex:0], you end up with the NSInvalidArgumentException and a crash.
We are allowed to create only two text fields in alertview. Here:
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Change Password"
message:#""
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK", nil];
alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
UITextField * alertTextField1 = [alert textFieldAtIndex:0];
alertTextField1.keyboardType = UIKeyboardTypeDefault;
alertTextField1.placeholder = #"Type Current password";
[[alert textFieldAtIndex:0] setSecureTextEntry:YES];
UITextField * alertTextField2 = [alert textFieldAtIndex:1];
alertTextField2.keyboardType = UIKeyboardTypeDefault;
alertTextField2.placeholder = #"Type New Password";
[alert show];
Here is the solution for your question..
http://www.alterplay.com/ios-dev-tips/2009/12/username-and-password-uitextfields-in-uialertview-prompt.html

Resources