繁体   English   中英

将手势识别器添加到特定的UITabBarController tabBarItem

[英]Add Gesture Recognizer to specific UITabBarController tabBarItem

我正在尝试将手势识别器添加到特定的tabBar项的子视图。 我可以成功地将一个添加到tabBar本身,但不能添加一个特定的索引。

通过在AppDelegate中实现此功能,我能够诱使它根据selectedIndex做出反应:

[self.tabBar.view addGestureRecognizer:longPressNotificationsGR];

-(void)showFilterForNotifications:(UILongPressGestureRecognizer *)gesture {

  if (self.tabBar.selectedIndex == 4) {
      if (gesture.state == UIGestureRecognizerStateBegan) {
          NSLog(@"Began");
      } else if (gesture.state == UIGestureRecognizerStateEnded) {
          NSLog(@"Ended");
      }
  }
}

有没有更好的办法? 是的,我知道这不是苹果公司的初衷,但这正是我特定项目所需要的。 我只是觉得这不是最好的解决方法,即使有解决方法,我也不知道这是怎么回事,因为它在AppDelegate中表现良好。 但是最终,我不想这样做,我想将其添加到objectAtIndex:n这样即使当前选择的索引为4,用户也不能只是按住tabBar的任何位置。 现在,如果选择了4,则用户可以点击并按住索引1图标,然后调用手势方法。 我希望它仅在用户点击并按住objectAtIndex:n

您可以使用UITabBar上的以下类别方法在特定索引处获取选项卡的UIView:

- (UIView*)tabAtIndex:(NSUInteger)index
{
    BOOL validIndex = index < self.items.count;
    NSAssert(validIndex, @"Tab index out of range");
    if (!validIndex) {
        return nil;
    }

    NSMutableArray* tabBarItems = [NSMutableArray arrayWithCapacity:[self.items count]];
    for (UIView* view in self.subviews) {
        if ([view isKindOfClass:NSClassFromString(@"UITabBarButton")] && [view respondsToSelector:@selector(frame)]) {
            // check for the selector -frame to prevent crashes in the very unlikely case that in the future
            // objects that don't implement -frame can be subViews of an UIView
            [tabBarItems addObject:view];
        }
    }
    if ([tabBarItems count] == 0) {
        // no tabBarItems means either no UITabBarButtons were in the subView, or none responded to -frame
        // return CGRectZero to indicate that we couldn't figure out the frame
        return nil;
    }

    // sort by origin.x of the frame because the items are not necessarily in the correct order
    [tabBarItems sortUsingComparator:^NSComparisonResult(UIView* view1, UIView* view2) {
        if (view1.frame.origin.x < view2.frame.origin.x) {
            return NSOrderedAscending;
        }
        if (view1.frame.origin.x > view2.frame.origin.x) {
            return NSOrderedDescending;
        }
        NSLog(@"%@ and %@ share the same origin.x. This should never happen and indicates a substantial change in the framework that renders this method useless.", view1, view2);
        return NSOrderedSame;
    }];

    if (index < [tabBarItems count]) {
        // viewController is in a regular tab
        return tabBarItems[index];
    }
    else {
        // our target viewController is inside the "more" tab
        return [tabBarItems lastObject];
    }
    return nil;
}

然后,您只需要添加手势识别器:

[[self.tabBarController.tabBar tabAtIndex:4] addGestureRecognizer:myGestureRecognizer];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM