0

我真的被这个案子困了一周。我在 UINavigationItem 中有一个 UIBarButtonItem,层次结构是这样的

替代文字

BarButtonItem 是segmentedControl 的包装。UIBarbuttonitem 和 UIsegmentedControl 是通过编程方式制作的,但其他的是在 IB 中制作的。

在这种情况下,我想在按下或触摸 barbuttonitem 后显示一个视图。在我在这个论坛上阅读的几个线程中,我知道 UIBarbuttonItem 没有继承 UIResponder,所以我选择 NavigationBar 来获得触摸,并为它定义了一个框架。

这是我制作的代码:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
 navBar = self.navigationController.navigationBar;
 int index = _docSegmentedControl.selectedSegmentIndex;
NSLog(@"index di touches began : %d", index);
CGFloat x;

if (index == 0) {
    x = 0.0;
 }else if (index == 1) {
      x = widthSegment + 1;
 }else if (index == 2) {
      x = 2*widthSegment + 1;
 }else if (index == 3) {
      x =   3*widthSegment+ 1;
 }else if (in   dex == 4) {
      x = 4*widthSegment + 1;
}

CGRect frame = CGRectMake(x, 0.00, widthSegment, 46.00);

 UITouch *touch = [touches anyObject];
 CGPoint gestureStartPoint = [touch locationInView:navBar];

NSLog(@"gesturestart : %f, %f", gestureStartPoint.x, gestureStartPoint.y);

 if (CGRectContainsPoint(frame, gestureStartPoint)) {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(segmentItemTapped:) object:[self navBar]];
    NSLog(@"cancel popover");
}
}

navBar 在 myViewController.h 中声明,我将其设置为 IBOutlet。

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
 int index = _docSegmentedControl.selectedSegmentIndex;
 NSLog(@"index di touches ended : %d", index);
 navBar = self.navigationController.navigationBar;
 CGFloat x;

 if (index == 0) {
      x = 0.0;
 }else if (index == 1) {
      x = widthSegment + 1;
 }else if (in   dex == 2) {
      x = 2*widthSegment + 1;
 }else if (index == 3) {
      x = 3*widthSegment+ 1;
 }else if (index == 4) {
      x = 4*widthSegment + 1;
}

 CGRect frame = CGRectMake(x, 0.00, widthSegment, 46.00);

 UITouch *touch = [touches anyObject];
 CGPoint gestureLastPoint = [touch locationInView:navBar];

 NSLog(@"lastPOint : %d", gestureLastPoint);

if (CGRectContainsPoint(frame, gestureLastPoint)) {
    if (touch.tapCount <= 2) {
           [self performSelector:@selector(segmentItemTapped:) withObject:nil afterDelay:0.0];
    }
}
}

当我点击工具栏而不是导航栏中时检测到 touchesBegan 和 touchesEnded。

我确实实现了这样的 hitTest 方法:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *touchedView = [super hitTest:point withEvent:event];
    NSSet* touches = [event allTouches];
    // handle touches if you need
    return touchedView;
}

但它仍然没有好转。

有人可以描述为什么会这样?问候
-Risma-

4

1 回答 1

0

您可以简单地向 barbutton 项目添加一个动作,例如

[self.mybarbutton setAction:@selector(barButtonTapped:)];  

[self.mybarbutton setTarget:self];
于 2010-12-16T12:39:29.850 回答