Search code examples
iosloopsuibuttonhiddenuiswipegesturerecognizer

Use iOS SwipeGesture To Cycle through UIButtons


I have 6 UIButtons set up in my UIView, all in the exact same location. What I want to do, is to swipe from left to right or right to left, in order to go through the buttons.

I have the UIGestures all set up and working on the view, I am just not sure the best way to go about cycling through these UIButtons.

I was thinking that it could be simple enough to tag each UIButton and HIDE all but one, but am not sure about the best way to loop through these.


Solution

  • Just put them in an NSMutableArray and whatever button is at index 0 is the visible one, as they swipe you'd remove the button at index 0, set it to hidden = YES and add it to the end of the array then set the button at index 0's hidden = NO.

    Assuming you're using ARC, inside your class' implementation (.m) file:

    @interface MyFancyButtonClass () {
        NSMutableArray *_swipeButtons;
    }
    

    inside your viewDidLoad:

    _swipeButtons = [NSMutableArray arrayWithObjects:buttonOne, buttonTwo, buttonThree, buttonFour, nil];
    buttonOne.hidden = NO;
    buttonTwo.hidden = buttonThree.hidden = buttonFour.hidden = YES;
    

    inside your gestureRecognizer:

    UIButton *currentVisibleButton = [_swipeButtons firstObject];
    UIButton *nextVisibleButton = [_swipeButtons objectAtIndex:1];
    
    [_swipeButtons removeObject:currentVisibleButton];
    [_swipeButtons addObject:currentVisibleButton];
    
    currentVisibleButton.hidden = YES;
    nextVisibleButton.hidden = NO;