質問

I'm quite new in ios development

Here I'm trying to make a basic calculator concept

@interface ViewController : UIViewController{
IBOutlet UILabel* myLabel;

int sum;
}

 -(IBAction)onePressed:(id)sender{
printf("1");

UIButton* button1 = sender;

NSString* button1Text = button1.titleLabel.text;

int value = [button1Text intValue];

// String.format("value: %d", value);
myLabel.text = [NSString stringWithFormat:@"value: %d", value];
}

-(IBAction)twoPressed:(id)sender{
printf("2");

UIButton* button2 = sender;

NSString* button2Text = button2.titleLabel.text;

int value = [button2Text intValue];

// String.format("value: %d", value);
myLabel.text = [NSString stringWithFormat:@"value: %d", value];
}

-(IBAction)threePressed:(id)sender{
printf("3");

UIButton* button3 = sender;

NSString* button3Text = button3.titleLabel.text;

int value = [button3Text intValue];

// String.format("value: %d", value);
myLabel.text = [NSString stringWithFormat:@"value: %d", value];
}

I have make 3 buttons

when the user click one of those buttons, the value will be sum up with the previous value and the value will be shown in the label

anyone know how to do it?

thanks

役に立ちましたか?

解決 2

You already have the iVar sum in place - you just need to total it with every button press. As @Wain suggested, you should change to NSInteger rather than int, but either way will work.

Also, since you are using the value of the button, you only need a single action handler for all of your buttons - in IB, just connect the touchUpInside to a single IBAction buttonPressed:(id)sender

-(IBAction) buttonPressed:(id)sender
{
    UIButton *button=(UIButton *)sender;
    sum += [button.titleLabel.text intValue];
    myLabel.text = [NSString stringWithFormat:@"value: %d",sum];
}

Also, while there is nothing wrong with using an iVar, it is preferable to use properties -

@interface ViewController : UIViewController

@property (weak,nonatomic) IBOutlet UILabel *mylabel;
@property NSInteger sum;

@end

-(IBAction) buttonPressed:(id)sender
{
    UIButton *button=(UIButton *)sender;
    self.sum += [button.titleLabel.text intValue];
    self.myLabel.text = [NSString stringWithFormat:@"value: %d",self.sum];
}

他のヒント

Add tags to you buttons. For example twoButton.tag = 2; or do it in the Interface Builder.

Change your code (at least) to:

@interface MyClass ()
@property (nonatomic, assign) NSInteger currentValue;
@end


@implementation MyClass

- (IBAction)twoPressed:(UIButton*)sender {
    NSLog(@"twoPressed");

    self.currentValue += sender.tag;

    myLabel.text = [NSString stringWithFormat:@"value: %d", self.currentValue];
}

@end

Add a property to store the current value. As each button is pressed, add the new value to it and store that result (and show it on the label).

Try to use NSInteger instead of int.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top