UIStepper: how to be aware which button (minus or plus button) of the stepper has been clicked by user

◇◆丶佛笑我妖孽 提交于 2019-12-07 06:59:40

问题


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...



来源:https://stackoverflow.com/questions/17433679/uistepper-how-to-be-aware-which-button-minus-or-plus-button-of-the-stepper-ha

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!