我尝试将手势识别器添加到特定的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");
}
}
}
有更好的方法吗?是的,我知道这不是Apple的想法,但这是我对我的特定项目所需要的。我觉得这不是最好的解决方法,如果有一个,我不确定它在AppDelegate中的性能如何。但最终,我不想这样做,我想将它添加到objectAtIndex:n
,这样用户就可以按住tabBar上的任意位置,即使4是当前的选定的指数。现在用户可以点击&保持索引1图标,如果选择4,则调用手势方法。我希望它只在用户点击时才会发生。坚持objectAtIndex:n
答案 0 :(得分:-1)
您可以在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];