set variable to 'YES' for each edited Textfield using UIControlEventEditingChanged - ios

I want to keep track of edited textfields. I would like to store every edited textfield in a variable. Then when the user press the 'save' button it updates the edited textfield in the database.
I want to know how i can, in "(void)textChanged:' specify what textfield is being changed and then store it in a variable (array?). Then i want to pick out the edited textfield names from the array and execute a -(void).
Example:
* testTextfield gets edited.
* Add the edited textfieldname and store it in an Array
* Extract the edited textfields from the array
* Execute a -(Void) with the edited textfields
.h file:
#property (nonatomic, strong) NSMutableArray *allEditedTextfields;
.m file:
[testTextField addTarget:self action:#selector(textChanged:) forControlEvents:UIControlEventEditingChanged];
Here i want to identify what textfield got edited and store it in the Array.
-(void)textChanged:(UITextField *)textField
{
[allEditedTextfields addObject:textField.text];
}
This is when i press the 'save' button:
-(IBAction)btnSaveHorse:(id)sender{
NSLog(#"Array - %#", allEditedTextfields);
}
And when i press the save button it says (Array - (null))
-(void)textChanged: will be executed everytime a new letter or number is being typed.
Please help me!

First off, you probably don't want to add an object to an array each time something is typed in a text field. What you might want to do is use an NSMutableDictionary to store values for each text field.
You could give each text field a unique tag either in the interface file or in code using:
yourObject.tag = 1; //Or whatever
Then, you'd need an NSMutableDictionary. You must initialize the dictionary (I'm assuming you didn't initialize your array, which is why you were getting (null)).
#property (nonatomic, strong) NSMutableDictionary *allEditedTextfields; //.h
allEditedTextfields = [NSMutableDictionary new]; //viewDidLoad of .m
Then, inside your textChanged: function, use the tag as the key of a NSNumber-wrapped boolean indicating that your text field has been edited. This will also ensure that there aren't any duplicates (it'll overwrite anything at the existing key if there is anything):
-(void)textChanged:(UITextField *)textField
{
[allEditedTextfields setObject:#TRUE forKey:#(textField.tag)];
}
Lastly, whenever you're ready to upload your data to a database, just loop through the dictionary and use viewWithTag to get the text field.
for (NSNumber *key in allEditedTextfields) { //Loop through all keys
if ([[dict objectForKey:key] boolValue] == TRUE) { //See if it was edited
UITextField *tField = (UITextField *)[self.view viewWithTag:[key intValue]];
//save your data using tField.text
}
}
[allEditedTextfields removeAllObjects]; //Remove the objects when you're done so it doesn't upload the same ones next time unless they're edited again

Related

How to increase UILabel value on every click of UIButton?

I am working with a UILabel and assign some string value on it, now I want to update its value every time when I click on UIButton. See me IBAction code.
- (IBAction)IncreasePack:(id)sender {
int increseprice = [value intValue];
int updateprice = [price intValue];
NSString *newprice= [NSString stringWithFormat:#"%d", increseprice+updateprice];
_TotalPrice.text = newprice;
NSLog(#"newprice %#",newprice);
}
When I click button the first time, my logic executes fine. But when I tap again the code is not executed but its print every time on every click.
Try this:
in .h file
#property (strong, nonatomic) int labelValue;
in .m file
- (void)viewWillAppear{
self.labelValue = 0;
}
- (IBAction)buttonClicked:(UIButton *)sender{
self.labelValue++;
[self.label setText:[NSString stringWithFormat:#"%d", self.labelValue]];
}
Your code does not make sense. Your IBAction calculates newprice from increseprice+updateprice. If increseprice and updateprice don't change, the sum of those values won't change either.
You need an instance variable that hold the current value, and when the user clicks your button you need to add the increase value to that previous value and update the total
Instead you always say
newprice = increseprice + updateprice
Nowhere do you save the new total. Click the button again and neither increseprice update price will have changed, so newprice will still be the same value.

Updating UILabel.Text inside of a for loop after a button is pressed

I have a UIViewController, and in that I have an array of questions that I pull from a sqlite3 query. I am then using a for loop to iterate through each question in the array to change the UILabel.text to display the question on the screen. This is actually working for the first question in the array!
I then have four buttons for answers. I want to make it so if one of the buttons is pressed, the answer is saved and the next question in the loop updates the UILabel.text.
The four answers never change as it is more of a survey than answers, so one of the answers is "I agree" or "disagree", so the button text never changes.
Is this possible?
I have been on here and Google to find a way to link the button pressed with completing each iteration of the loop without any luck.
Why are you iterating through questions and changing UILabel's text? Shouldn't be it changed only on tapping one of the survey buttons?
If I got you correctly, you should do following:
1) Declare three properties in your controller: NSArray *questions, NSMutabelArray *answers, NSInteger currentIndex;
2) Init/alloc them in viewDidLoad (except currentIndex, of course, set it to 0).
3) Fill up questions array with your question strings.
4) Set text to UILabel, label.text = questions[currentIndex];
5) create IBAction method and link it to all survey buttons.
6) in IBAction method, insert button's title to answers array and show next question.
- (void)viewDidLoad {
[super viewDidLoad];
self.questions = {your questions array};
self.answers = [[NSMutableArray alloc] init];
self.currentIndex = 0;
}
- (IBAction)btnClicked:(id)sender {
UIButton *btn = (UIButton *)sender;
NSString *title = btn.titleLabel.text;
[self.answers addObject:title];
currentIndex++;
label.text = questions[currentIndex];
}
I hope you will understand the code.
In short, yes this is possible.
You'll first want to keep track of the question that your user is currently on. You can do this by storing an index in an instance variable or, if you plan on allowing the user to open the app and start from where they left off, you can use NSUserDefaults, which writes to disk and will persist.
// In the interface of your .m file
int questionIndex;
// In viewDidLoad of your controller, however this will start for index 0, the beginning of your questions array
questionIndex = 0
By storing the index in NSUserDefaults, you can grab it in ViewDidLoad, and start from where the user last left off:
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:questionIndex] forKey:#"questionIndex"];
To store your answer, you could add a method for your buttons called answerTapped:,
- (void)answerTapped:(UIButton *)answerButton
{
// Grab the answer from the text within the label of the button
// NOTE: This assume your button text is the answer that you want saved
NSString *answer = answerButton.titleLabel.text;
// You can use your questionIndex, to store which question this answer was for and you can then take the answer and store it in sqlite or where you prefer...
}
You can add this method to your buttons like so
[answerButton addTarget:self action:#selector(answerTapped:) forControlEvents:UIControlEventTouchUpInside];
You could then write a method to increment questionIndex now that an answer button has been pressed.
- (void)incrementQuestionIndex
{
// Increment index
questionIndex += 1;
// Update and save value in UserDefaults
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:questionIndex] forKey:#"questionIndex"];
}
You could then call a separate, final method to update the question label.
- (void)updateQuestionLabel
{
// Grab the question using the index (omit this line and go straight to the next if storing the index in an iVar)
questionIndex = [[[NSUserDefaults standardUserDefaults] objectForKey:#"questionIndex"] integerValue];
// Grab the question using the index. Assumes you have a questions array storing your questions from sqlite.
NSString *question = [questions objectAtIndex:questionIndex];
// Update the question UILabel
[questionLabel setText:question];
}

UILabel Doesn't populate random strings chosen from NSMutable Array

I am trying to populate a UILabel with strings randomly chosen from an array. For some reason, the random choosing from array doesn't occur (the label always displays the first element of the array).
//.h file has declaration as follows
NSMutableArray *array;
//.m file
- (void)viewDidLoad
{
array = [[NSMutableArray alloc] initWithObjects: #"abc", #"def", nil];
}
and then, I have a method called orientationPopulate that does this:
-(void)labelPopulate;
{
int randomArrayIndex = arc4random() % array.count;
//Setting the label's text
_label.text = array[randomArrayIndex];
}
Based on the label displayed randomly, I would click buttons on the screen. So the label must keep changing each time. I do not know if I'm missing some link here. Can somebody help?
randomArrayIndex is 0 or 1, it may not change every time you click the button

NSMutableArray UIButton Press History

I currently have an array of buttons being generated which works great. Outside of this on touch up inside each button calls on a -(void)onTouch function where some math is done to determine an action. This all works great except I would like to store a history of the pressed buttons. I've tried many different ways to create an NSMutableArray and store the values of the pressed buttons, but because I can only declare the array within the -onTouch action, every time a button is pressed the array is reset so it never remembers more than one move. If I try to declare the array in my header and synthesize it outside I either get the error that nsmutable array is not a compile time thinger or it doesn't store anything (log output is "(null)". Can someone paste in some code on how to declare an array that can store and append the uibutton tags outside of where the uibutton press event happens? I'll post code later tonight if this isn't clear.
Cheers
You need to not only declare the array, but also initialise it. If you don't initialise, you won't necessarily get a warning, but you will get lots of nil data.
You only want to initialise the array once (as you have noticed) so viewDidLoad is a good place to do it. Another good place is in a custom accessor...
- (NSMutableArray*)historyArray
{
if (!_historyArray) {
_historyArray = [[NSMutableArray alloc] init];
}
return _historyArray;
}
Now the first time you try to [self.historyArray addObject:sender], the accessor will note the absence of a historyArray, create one and return it. Next time round it won't be recreated as it already exits.
#property(nonatomic,retain)NSMutableArray *tapCollection;
-(void)viewDidLoad{
self.tapCollection = [[NSMutableArray alloc] init];
}
-(void)onTouch:(id)sender{
UIButton *btnTapped = (UIButton *)sender;
[self.tapCollection addObject:[NSNumber numberWithInt:btn.tag]];
}

Editing multiple dynamically generated UITextFields at runtime

I have made an application in which user may generate as many UITextField as he/she wants and those will be automatically placed over a UIView. Functionality is that user may drag the any of the UITextField at any point of screen.Till this part every thing is quite working. Now if he wants to edit the UITextField he taps(2 times) on UITextField and edits.This part of mine is only working for the recent generated UITextField not for all. How can i do this? I fnay one wants my previous code i can post. Plese respond it sonn. Thanks in advance.
add textFieldArray to .h file then specify <UITextFieldDelegate> and
sythesize that array.
while creating the each textfield
specify delegate like this
mytextF1.delegate=self;
mytextF2.delegate=self;
.....
after that add all text field object to an textFieldArray which should be declared .h file and synthesize them .(dont forget to alloc and init this array in ur viewdidload).
self.textFieldArray=[[NSMutableArray alloc]init];
then add each text field to this array
[self.textFieldArray addObject:mytextF1];
[self.textFieldArray addObject:mytextF2];
.......
then use this delegate methode to update
- (void)textFieldDidBeginEditing:(UITextField *)textField{
for (UITextField *textF in self.textFieldArray) {
[textF setText:[textField text]];
}
}

Resources