导航栏导航项导致推送视图控制器上按钮的顶部区域不可点击

Navigation Bar Navigation Items causing top area of buttons on pushed view controller to not be tappable

我有一种强烈的感觉,这可能是 Xcode 苹果需要修复的一个错误。我有一个作为根控制器嵌入在导航控制器中的视图控制器。视图控制器有一个与顶部布局指南垂直对齐的按钮。视图控制器的按钮工作正常,所有可点击区域都正常工作。

但是,如果我将相同或相似的视图控制器推送到导航堆栈,它的按钮将无法完全点击。按钮的顶部(大约 10 像素左右)不再可点击。如果我尝试点击按钮的左上角,则会点击导航栏上的后退按钮,即使我显然没有点击导航栏边界。我认为这是苹果的一个错误,但我想知道是否有人知道修复方法。如果有人需要,这里是link to the github project

这是 iOS 的默认行为。许多 UIView 在 iOS 中具有此扩展触摸功能。例如,UINavigationBarUITabBarUISecgmentedControl 等。我相信这是为了更容易触摸这些控件。

如果您仍想覆盖此默认行为。您可以通过子类化 UINavigationBar 并在子类中添加此方法来做到这一点:

-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {

    if ([self pointInside:point withEvent:event]) {
        self.userInteractionEnabled = YES;
    } else {
        self.userInteractionEnabled = NO;
    }

    return [super hitTest:point withEvent:event];
}

已向您的 Github project 发出合并请求。

这是解决方案的 swift 版本,以备不时之需:

class CustomNavBar: UINavigationBar {

  override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
    if pointInside(point, withEvent: event) {
      userInteractionEnabled = true
    } else {
      userInteractionEnabled = false
    }

    return super.hitTest(point, withEvent: event)
  }
}

Swift 3 及以上:

override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
    isUserInteractionEnabled = self.point(inside: point, with: event)
    return super.hitTest(point, with: event)
}