How to increase UILabel value on every click of UIButton? - ios

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.

Related

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

how to insert number like in stack and delete like pop

I am using buttons and I assigned tag 0 to 10 . Then I made an action to get the clicked button's tag, and now I want to display the tag in a label . Also I have a cancel button C. If user wants to delete any number, he can click C button that I want to remove number from the label .
This is my screenshot to touch the number
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Ezywire";
addnum=[[NSMutableArray alloc]init];
numbber=[[NSString alloc]init];
}
- (IBAction)NumberAction:(id)sender {
NSInteger tagvalue = [sender tag];
NSString *current=[NSString stringWithFormat:#"%ld", (long)tagvalue];
[addnum addObject:current];
NSString *temp;
for ( int i=0; i<[addnum count]; i++) {
numbber=[numbber stringByAppendingString:[addnum objectAtIndex:i]];
}
NSLog(#"data===%#",numbber);
ValueLable.text= numbber;
}
But in the label I am getting repeated number like this. How to implement this.
For example if user enters 2 then in the label
2
then he enters 7 then in the label
27
then he entered 9 then in the label
279
........ like this .
If user clicks C, then it remove from label last value is (last value removed)
27
The problem in your code is that numbber is initialized when the view is loaded, and never gets cleared again. However, each time a button is pressed, the whole addnum of digits gets appended to num again, creating repeated digits.
Fix this by removing num as an instance variable, making it a local to NumberAction: method, and setting it to an empty string every time the number is pressed.
Since you are planning to support the clearing action as well, you should make a private method that combines the digits from addnum array into a string. This way your NumberAction: and ClearAction would share the code that formats the array and sets the label. Your NumberAction: method would append a number and call FormatAndSetLabel, while the ClearAction method would remove the last digit if it is available, and call FormatAndSetLabel as well:
- (IBAction)NumberAction:(id)sender {
NSInteger tagvalue = [sender tag];
NSString *current=[NSString stringWithFormat:#"%ld", (long)tagvalue];
[addnum addObject:current];
[self FormatAndSetLabel];
}
- (IBAction)ClearAction:(id)sender {
if (!addnum.count) return;
[addnum removeLastObject];
[self FormatAndSetLabel];
}
-(void)FormatAndSetLabel {
NSMutableString *temp = [NSMutableString string];
for ( int i=0; i<[addnum count]; i++) {
[temp appendString:addnum[i]];
}
ValueLable.text= temp;
}
Also it might be interesting for you to have a look at Paul's Hegarty Stanford iOS development course (iPad and iPhone Application Development, Fall 2011)
https://itunes.apple.com/ru/itunes-u/ipad-iphone-application-development/id473757255?mt=10
Calculator app is used here as an example. Must see for the beginners.

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

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

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

reading numbers from UIbutton

I'm new in Objective-c and Xcode. I'm trying to get large numbers from certain buttons but all I got is only one number. I'm using button tag for that.
For instance: if I want to add two numbers 2+3, it works well. but when I want to add 230+32, it doesn't.
Interface :
- (IBAction)getnumber:(id)sender;
#property (strong, nonatomic) IBOutlet UILabel *Result;
int number;
Implementation part:
-(IBAction)getnumber:(id)sender {
number = [sender tag];
Result.text = [NSString stringWithFormat:#"%i", number];
}
Is there any way to get a large number from button's tag, if I tapped more than one button?
Thank you in advance .
Your problem comes from how you are defining your variables. If I understand your setup right, you have something like a calculator interface, and you are only setting button's tags to single digit numbers like 1, 2, 3, ... to indicate the next digit to display?
In that case your line number = [sender tag] will set a global variable to that button's number (remember when your CS prof told you never to use globals? Here's a reason why!) Since you just overwrote number with this button's tag when you go to set your result string in the next line, number only holds the value of the last button pressed. Instead you should do something like this.
#interface MyClass : UIViewController
#property (nonatomic, strong) IBOutlet UITextView * resultLabel;
- (IBAction)getNumber:(id)sender;
#end
and
- (IBAction)getNumber:(id)sender;
{
self.resultLabel.text = [NSString stringWithFormat:#"%#%d", self.resultLabel.text, [sender tag]];
}
In this way, every time getNumber: is called, it takes whatever text the label is currently displaying and append's this button's value. As a side note, its conventional to start Objective-C property names with a lowercase letter.
I think you have to attach a variable type to number. It should be -
- (IBAction)getnumber:(id)sender
{
NSInteger number = [sender tag];
Result.text = [NSString stringWithFormat:#"%i", number];
}
I
You need to change your logic.
number = 0;
if button with number is clicked
number = number * 10 + button.tag;
else
if operation (not =) is pressed
store the number and operator
if = operatior is clicked
perform the operation on stored number and recently entered number.

Resources