MiguelB
MiguelB

Reputation: 1913

Play/stop UIButton toggle using selected property for state not working

I can't see what the problem is with my code. Nothing happens when I press the button, like as if the default state wasn't even set, which is weird because we can't do something playButton.state = UIControlStateNormal since the state property is read-only.

This is my code:

- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {

    // ...

    playButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    playButton.frame = CGRectMake(100, 500, 100, 50);
    [playButton setTitle:@"play" forState: UIControlStateNormal];
    [playButton setTitle:@"stop" forState: UIControlStateSelected];
    playButton.exclusiveTouch = YES;
    playButton.selected = NO;
    [playButton addTarget:self action:@selector(play) forControlEvents:UIControlEventTouchUpInside];

and

- (void) play {

    if (playButton.state == UIControlStateNormal) {

        playButton.selected = YES;

        CABasicAnimation *maskAnim = [CABasicAnimation animationWithKeyPath:@"position.x"];
        maskAnim.byValue = [NSNumber numberWithFloat:diagramWidth];
        maskAnim.repeatCount = HUGE_VALF;
        maskAnim.duration = 1.750f;
        [self.maskLayer addAnimation:maskAnim forKey:@"position.x"];
        self.diagramLayer.mask = maskLayer;

        [backImageLayer addSublayer: self.diagramLayer];


        [audioPlayerNormal play];
        [moviePlayerNormal play]; 


    }
        else if (playButton.state == UIControlStateSelected) {

            playButton.selected = NO;

            [self.maskLayer removeAnimationForKey:@"position.x"];
            self.diagramLayer.mask = nil;

            [audioPlayerNormal stop];
            [moviePlayerNormal stop];

        }

}

Upvotes: 0

Views: 1538

Answers (1)

user745098
user745098

Reputation:

The following code should do the job.

- (void) play {

    if (playButton.selected == NO) {

        CABasicAnimation *maskAnim = [CABasicAnimation animationWithKeyPath:@"position.x"];
        maskAnim.byValue = [NSNumber numberWithFloat:diagramWidth];
        maskAnim.repeatCount = HUGE_VALF;
        maskAnim.duration = 1.750f;
        [self.maskLayer addAnimation:maskAnim forKey:@"position.x"];
        self.diagramLayer.mask = maskLayer;

        [backImageLayer addSublayer: self.diagramLayer];


        [audioPlayerNormal play];
        [moviePlayerNormal play]; 


    }
    else {
        [self.maskLayer removeAnimationForKey:@"position.x"];
        self.diagramLayer.mask = nil;

        [audioPlayerNormal stop];
        [moviePlayerNormal stop];

    }
    playButton.selected = !playButton.selected;
}

Upvotes: 2

Related Questions