Search code examples
iosxcodebuttonuibuttoncore-motion

Create a single button which can trigger two actions and changes it's title?


CGRect buttonFrame = CGRectMake( 10, 80, 100, 30 );
UIButton *button = [[UIButton alloc] initWithFrame: buttonFrame];
[button setTitle: @"Start" forState: UIControlStateNormal];
[button addTarget:self action:@selector(start_Accel) forControlEvents:UIControlEventTouchUpInside];
[button setTitle: @"Stop" forState: UIControlEventTouchUpInside];
[button addTarget:self action:@selector(stop_Accel) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:button];

I want to create a button that can start and stop accelerometer updates as user presses it, But it's title too should change from start to stop and also it should continues until user reset everything by an anoterh button, but i have no idea of getting it done, except the following code, But it doesnt change the title and call stop action?

Thank you in advance!


Solution

  • Manage the state of the button in some kind of was eg. with a @property and use just one action:

    in you .h

    @property (nonatomic) BOOL startStopButtonIsActive;
    

    in your .m

    @synthesize startStopButtonIsActive = _startStopButtonIsActive;
    
     ....
    
    - (void)viewDidLoad {
           [button addTarget:self action:@selector(startStopButtonPressed) forControlEvents:UIControlEventTouchUpInside];
          // other stuff
    }
    
    - (void)startStopButtonPressed {
        if (startStopButtonIsActive) {
            self.startStopButtonIsActive = !self.startStopButtonIsActive  //toggle!
            // do your stuff here
        } else {
            self.startStopButtonIsActive = !self.startStopButtonIsActive  //toggle!
            // do your stuff here
        }
    }