UIStepper: how to be aware which button (minus or

2019-05-04 12:59发布

问题:

How do I possibly know which button(minus or plus button) of the stepper has been clicked by user?

- (IBAction)buttonStepper:(id)sender {
    int stepperValue = self.outletStepper.value;
    self.label.text = [NSString stringWithFormat:@"%d", stepperValue];
}

thanks :3

回答1:

You can, instead of addTarget:action, observe the steppers value property and ask to receive both old and new value in the change dictionary

{
    UIStepper *stepper = ...;
    [stepper addObserver:self forKeyPath:@"value"
                 options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                 context:0];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (object == stepper) {
        double oldValue = change[NSKeyValueChangeOldKey];
        double newValue = change[NSKeyValueChangeNewKey];
        double change = newValue - oldValue;
    }
}

or subclass UIStepper and do the calculation in an overridden -setValue:



回答2:

- (void)viewDidLoad
{
     [super viewDidLoad];
     oldValue=stepperObj.value;
}

- (IBAction)stepperStep:(id)sender {

if (stepperObj.value>oldValue) {

    oldValue=oldValue+1;
    NSLog(@"%d",oldValue);
    //your code do you want to perform on increment
}
else
{
    oldValue=oldValue-1;
    NSLog(@"%d",oldValue);
    //your code do you want to perform on decrement
}

}

You have to declare an oldValue as an integer in header file...



标签: ios uistepper