Search code examples
objective-cuigesturerecognizeruitabbaruilongpressgesturerecogni

Handle long press on a single UITabBarItem


I use the long press gesture on a tab bar. But I only need the long press gesture for one particular tab bar item.

How can I solve this problem? Could I customize the long press gesture in tab bar?


Solution

  • You can subclass UITabBarController and add a UILongPressGestureRecognizer to it's tabBar. Acting as the delegate of the gesture recognizer will allow you to be selective over when it will detect a long press. Since the tab bar item will be selected as soon as the user touches it you can use the selectedItem property to perform this check.

    @interface TabBarController () <UIGestureRecognizerDelegate>
    @property (nonatomic, strong) UILongPressGestureRecognizer *longPressRecognizer;
    
    @end
    
    @implementation TabBarController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        self.longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(recognizerFired:)];
        self.longPressRecognizer.delegate = self;
        [self.tabBar addGestureRecognizer:self.longPressRecognizer];
    }
    
    - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    
        // This will ensure the long press only occurs for the
        // tab bar item which has it's tag set to 1.
        // You can set this in Interface Builder or in code
        // wherever you are creating your tabs.
        if (self.tabBar.selectedItem.tag == 1) {
            return YES;
        }
        else {
            return NO;
        }
    
    }
    
    - (void)recognizerFired:(UILongPressGestureRecognizer *)recognizer {
        // Handle the long press...
    }
    
    @end