Dương Trần
Dương Trần

Reputation: 13

Calculator label string displaying

I'm new to Objective-C and trying to make a calculator. My problem is I can't add the new number when button is pressed to the string no matter what I use (I tried methods appendString/Format and stringByAppendingString/Format).

Inputting numbers. I do the same for every other numbers:

- (IBAction)btn9:(id)sender {

[self tabbedNumber:9]; }

Declare the variable:

@property NSString *labelString;

Getting the number function:

-(void)tabbedNumber:(int)num{
    NSString *lblStr = [[NSString alloc]init];

   lblStr = [lblStr stringByAppendingString:[@(num) stringValue]];
   self.labelString = lblStr;

   [self updateText];
}

Displaying on calculator with a label calLabel:

- (void)updateText{
    self.calLabel.text = self.labelString;

Best Anwser by @pavelTerziyski:

You keep lblStr = [lblStr stringByAppendingString:[@(num) stringValue]] in the function but the creation of the variable must be in the view didLoad - (void)viewDidLoad { [super viewDidLoad]; self.lblStr = [NSString new]; }

Upvotes: 1

Views: 118

Answers (3)

pavelTerziyski
pavelTerziyski

Reputation: 56

How you get the (int)num - because i tried your code with this and it worked perfectly fine

- (IBAction)buttonAction:(UIButton *)sender {

NSString *lblStr = [[NSString alloc]init];

lblStr = [lblStr stringByAppendingString:sender.titleLabel.text];
self.labelString = lblStr;

[self updateText];
}

- (void)updateText{

self.numberLabel.text = self.labelString;
}

Upvotes: 0

itsamirhn
itsamirhn

Reputation: 1

Try this method 👇

- (IBAction)tabbedNumber:(UIButton *)sender{

     self.labelString.text = [self.labelString.text stringByAppendingString:sender.titleLabel.text];

}

With this you can add any button's title label text to your label string. But you should connect number buttons to this method.

if you want to update label with another method try this 👇

- (IBAction)tabbedNumber:(UIButton *)sender{

     [self updateText:sender.titleLabel.text];

}

- (void)updateText:(NSString *)tappedNumberString{

     self.labelString.text = [self.labelString.text stringByAppendingString:tappedNumberString]; 

}

Don't forget to connect tabbedNumber method to number Buttons.

Upvotes: 0

vadian
vadian

Reputation: 285079

Appending something to a new created string is not very useful.

You need to append the integer (as text) to the property labelString which seems to hold the actual value of the label.

-(void)tabbedNumber:(int)num{
   self.labelString = [self.labelString stringByAppendingFormat:@"%i", num];
   [self updateText];
}

Upvotes: -1

Related Questions