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"];
Related
I have a login page with username,password textfield and a submit button.
If the focus is on password textfield and the user presses the submit button without pressing the return key on keyboard.
The keyboard is dismissed as i uses resignFirstResponder to dismiss the keyboard but when i hit the server and the alert comes of invalid credentials,then within nano seconds when alert is shown,keyboard also appears.
Used the below line of code to dismiss keyboard on Login Button click.
[self.passwdTxtFld setDelegate:self];
[self.usernameTxtFld setDelegate:self];
[self.view endEditing:YES];
Below is the code from where i get the response from server and also displays the alert.
- (void)checkLogin
{
NSLog(#"???%#",self.usernameTxtFld.text);
NSDictionary *checkLogin=[pwInteract initializeWithOrgId:#"JVVC" AppId:#"JVVC" LoginId:self.usernameTxtFld.text Password:self.passwdTxtFld.text];
NSLog(#"checklogin is %#",checkLogin);
if(checkLogin)
{
if(![[checkLogin objectForKey:#"NOTIFICATION"]isEqualToString:#"Y"] && ![[checkLogin objectForKey:#"NOTIFICATION"]isEqualToString:#"NV"]){
[loggingInAlert dismissWithClickedButtonIndex:loggingInAlert.cancelButtonIndex animated:YES];
[loggingInAlert removeFromSuperview];
NSLog(#"?? response is %#",checkLogin);
NSString *result = [checkLogin objectForKey:#"IS_AUTH"];
NSString *error = [checkLogin objectForKey:#"ERROR"];
if ([result isEqualToString:#"Y"] )
{
if([self.usernameTxtFld.text isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:#"username"]]){
[[NSUserDefaults standardUserDefaults] setObject:#"olduser" forKey:#"usertype"];
}
else{
[[NSUserDefaults standardUserDefaults] setObject:#"newuser" forKey:#"usertype"];
}
[[NSUserDefaults standardUserDefaults]setObject:#"" forKey:#"fetch"];
[[NSUserDefaults standardUserDefaults]setObject:#"" forKey:#"state"];
[[NSUserDefaults standardUserDefaults]setObject:#"success" forKey:#"state"];
[[NSUserDefaults standardUserDefaults]setObject:self.usernameTxtFld.text forKey:#"username"];
[self performSegueWithIdentifier:#"success" sender:nil];
}
else if (![error isEqualToString:#""])
{
UIAlertView *networkAlertView = [[UIAlertView alloc] initWithTitle:#"Error" message:error delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
networkAlertView.tag = 1;
[networkAlertView show];
[self.view endEditing:YES];
if([self.passwdTxtFld isFirstResponder]){
NSLog(#"pass");
}
if([self.usernameTxtFld isFirstResponder]){
NSLog(#"ddd");
}
}
else if ([result isEqualToString:#""])
{
NSString *error = [checkLogin objectForKey:#"ERROR"];
UIAlertView *networkAlertView = [[UIAlertView alloc] initWithTitle:#"Error" message:error delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
networkAlertView.tag = 3;
[networkAlertView show];
}
else
{
UIAlertView *networkAlertView = [[UIAlertView alloc] initWithTitle:#"" message:#"Oops! Either Username or Password is incorrect. Please type correct Username and Password to proceed." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
networkAlertView.tag = 3;
[networkAlertView show];
}
}
else if([[checkLogin objectForKey:#"NOTIFICATION"]isEqualToString:#"NV"]){
[customAlert hideActivityIndicator];
}
}
else
{
UIAlertView *networkAlertView = [[UIAlertView alloc] initWithTitle:#"Server Error" message:#"No Response From Server." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
networkAlertView.tag = 3;
[networkAlertView show];
}
}
On click event of login button have resigned both the username and password textfield,also the UITextFieldDelegate are connected.
Mistake:-
According to your code you are just resigning your keyboard in one "else if" condition:-
else if (![error isEqualToString:#""])
{
UIAlertView *networkAlertView = [[UIAlertView alloc] initWithTitle:#"Error" message:error delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
networkAlertView.tag = 1;
[networkAlertView show];
[self.view endEditing:YES];
What about the others else if condition, Things will be resolved if you resign keyboard [self.view endEditing:YES] in the very first statement of (void)checkLogin method.
Try [self.view endEditing:YES] when you tap login button or just before you show alert.
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[[self view] endEditing:YES];
}
or try
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
return YES;
}
// It is important for you to hide the keyboard
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
Also check UITextFieldDelegate delegate method
I'm getting a really weird error when woking with UIAlertViews. Been pulling my hair out over this, please help me out!
The error occurs when I press "Create!" in the alert1 alert and checkUsernameExists returns true and then I press "K." in alert3.
Code
-(void) newProfile:(id)sender {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"New Profile"
message:nil
delegate:self
cancelButtonTitle:#"Create!"
otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
UITextField *username = [alert textFieldAtIndex:0];
username.keyboardType = UIKeyboardTypeDefault;
username.placeholder = #"Desired Username";
UITextField *password = [alert textFieldAtIndex:1];
password.keyboardType = UIKeyboardTypeDefault;
password.placeholder = #"Desired Password";
[alert1 show];
}
- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex {
NSString *title = [alert title];
UITextField *username = [alert textFieldAtIndex:0];
UITextField *passwrod = [alert textFieldAtIndex:1];
if ([title isEqualToString:#"New Profile"]) {
if ([self checkUsernameExists:username.text] == false) {
// Create new account
}
else {
[self errorPop:#"New Profile"];
}
}
}
-(void) errorPop:(NSString*)who {
if ([who isEqualToString:#"New Profile"]) {
UIAlertView *alert3 = [[UIAlertView alloc] initWithTitle:#"OH NOOOOO"
message:#"Username is already taken please try another one."
delegate:self
cancelButtonTitle:#"K."
otherButtonTitles:nil];
[alert3 show];
}
}
Logs
2014-07-30 19:57:49.594 App[6532:a0b] * Terminating app due to
uncaught exception 'NSInvalidArgumentException', reason:
'textFieldIndex (0) is outside of the bounds of the array of text
fields'
The first alert view does not contain text fields, so when you request the first or second text field in -clickedButtonAtIndex:, you get an out of bounds exception.
You should distinguish which for which alert view you are receiving the callback. Try storing the alert views in a property upon creation, and then check for their identity in the callback before trying to access text fields.
Just set the delegate to nil for alert3 so it will not go under method "- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex".
Actually alert3 doesn't contain tetxfield and you have set delegate for this alert too so it is going to delegate method where they are trying to get UItextField but they don't have that's why it is crashing.
I have two buttons that will pop up an alertview with textfield to input data. However, only certain characters are allowed in each of the two textfields. Somehow, if I press the second button, the character set from the first button is used. What's going on here?
Also, what would be a more elegant form of inputting data without having to use an alertview? Could I use a modal view? If so, how?
- (IBAction)editRate
{
if(!self.powerOn) return;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Edit Jail Fee Rate"
message:#"Enter New Daily Rate"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[[alert textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex != alertView.cancelButtonIndex)
{
UITextField *field = [alertView textFieldAtIndex:0];
field.placeholder = #"Enter New Rate";
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789."] invertedSet];
if ([field.text rangeOfCharacterFromSet:set].location != NSNotFound)
{
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Only numbers are allowed in this field."delegate:self cancelButtonTitle:#"OK"otherButtonTitles:nil];
[errorAlert show];
FeeRate.text=#"0.00";
}
else
{
FeeRate.text = field.text;
[[NSUserDefaults standardUserDefaults] setObject:field.text forKey:RATE_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
else
{
}
}
- (IBAction)editDate
{
if(!self.powerOn) return;
UIAlertView *alertDate = [[UIAlertView alloc] initWithTitle:#"Edit Jail Fee Date"
message:#"Enter New Date"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok", nil];
alertDate.alertViewStyle = UIAlertViewStylePlainTextInput;
[[alertDate textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
[alertDate show];
}
- (void)alertDate:(UIAlertView *)alertDate clickedButtonAtIndex:(NSInteger)buttonIndex2
{
if (buttonIndex2 != alertDate.cancelButtonIndex)
{
UITextField *fieldDate = [alertDate textFieldAtIndex:0];
fieldDate.placeholder = #"Enter New Date";
NSCharacterSet * setnew = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789/"] invertedSet];
if ([fieldDate.text rangeOfCharacterFromSet:setnew].location != NSNotFound)
{
UIAlertView *errorAlert1 = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Only numbers and slashes are allowed in this field."delegate:self cancelButtonTitle:#"OK"otherButtonTitles:nil];
[errorAlert1 show];
FeeDate.text=#"00/00/0000";
}
else
{
FeeDate.text = fieldDate.text;
[[NSUserDefaults standardUserDefaults] setObject:fieldDate.text forKey:DATE_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
else
{
}
}
When a UIAlertView is dismissed then a function called
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
is called.
So, both your alert views call this function.
One way to tell which alertView is calling it, you could create an ivar or better two properties like this:
#property (nonatomic, strong) UIAlertView *rateAlert;
#property (nonatomic, strong) UIAlertView *dateAlert;
and you should initialize like this:
[self setRateAlert:[[UIAlertView alloc] initWithTitle...
[self.rateAlert show];
and
[self setDateAlert:[[UIAlertView alloc] initWithTitle...
[self.dateAlert show];
and then:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView==self.rateAlert) {
//do whatever for rateAlert
} else {
//do whatever with dateAlert
}
}
i want to do a simple alertView and ask for the phone number...
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"What is your phone number?"
message:nil
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Continue", nil];
message.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField* answerField = [message textFieldAtIndex:0];
answerField.keyboardType = UIKeyboardTypeNumberPad;
answerField.placeholder = #"+43 ...";
[message show];
And what do i have to put here into to check up something with the number (Like Mysql, etc.)
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
UITextField *textField = [alertView textFieldAtIndex:0];
?????????
// Something like if (textField == "090012345678") -> NSLog(#"WOW"); ...
}
If you don't know how to compare if two strings are the same then may I recommend that you seek out some basic tutorials on Objective-C.
if ([textField.text isEqualToString:#"090012345678"]) {
NSLog(#"WOW");
}
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