【问题标题】:UIButtonTypeInfoDark Touch AreaUIButtonTypeInfoDark Touch Area
【发布时间】:2012-12-06 14:59:48
【问题描述】:

我已将UIButton 类型为UIButtonTypeInfoDark 添加到视图中,并且它的触摸区域很大。我知道 Apple 推荐 44px,但在这种情况下,它要大一些。我为视图设置了浅灰色背景,以查看 44px 的结束区域在哪里,并且我可以在浅灰色视图区域之外触摸并仍然收到 infoTapped: 事件。

谁能解释一下为什么?谢谢!

_infoButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
[_infoButton setShowsTouchWhenHighlighted:NO];
[_infoButton setFrame:CGRectMake(frame.size.width-44, 0, 44, 25)];
[_infoButton setBackgroundColor:[UIColor lightGrayColor]];
[_infoButton addTarget:self action:@selector(infoTapped:) forControlEvents:UIControlEventTouchUpInside];

【问题讨论】:

  • 尝试设置中心而不是框架。然后 NSLog 它在 infoTapped 中的确切帧。我很想知道它的确切价值。
  • 我使用下面的代码,得到了下面的日志(x, y, width, height)。它必须将我的视图坐标之外的触摸区域重置为 44px 宽。 75.000000 0.000000 18.000000 18.000000 [_infoButton setFrame:CGRectMake(frame.size.width - 25, 0, 18, 18)]; [_infoButton setCenter:CGPointMake(frame.size.width-25+9, 9)];
  • 我会建议你检查这个问题Getting or setting the hit area of UIButtonTypeInfoLight。这不是一个解决方案,而是我这边的一点帮助。

标签: ios objective-c uibutton


【解决方案1】:

要解决这个问题很可能需要子类化。您可以在 UIButton 子类中覆盖 pointInside:withEvent: 并返回 NO,除非严格在按钮的范围内:

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    return CGRectContainsPoint(self.bounds, point);
}

Apple 控件有时会将 YES 返回到超出其范围的查询,以使控件更容易用手指触摸。

【讨论】:

    【解决方案2】:

    有一个更简单的版本来检查用户是否触摸了信息按钮边界的内部或外部。只需检查 touchInside 的状态即可。

    if ([control isKindOfClass:[UIButton class]]) {
        UIButton *btn = (UIButton*)control;
    
        if (btn.buttonType == UIButtonTypeInfoDark && btn.touchInside == YES) {
            // User pressed button inside bounds...
        } else if (btn.buttonType == UIButtonTypeInfoDark && btn.touchInside == NO) {
            // User pressed button outside bounds...
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      • 2019-08-08
      • 2017-11-26
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多