如何使未剪辑的子视图接收触摸事件?

时间:2011-03-11 21:06:22

标签: iphone objective-c cocoa-touch uibutton

我有一个小的自定义视图,我用作按钮。我用简单的UIButtonTypeCustom来实现这一点,我将其作为视图边界的子视图包含在内。但是,由于视图很小,我想增加命中目标的大小。通过将我的按钮的框架设置为大于自定义视图的边界并将clipsToBounds设置为NO,可以轻松完成(人们会想到)。这适用于可视化(自定义按钮在父视图外部绘制),但它不会在父视图之外的区域上接收touchUpInside个事件。如何使按钮接收touchUpInside个事件?

- (id) initWithFrame: (CGRect) frame {
  if (self = [super initWithFrame: frame]) {
    self.backgroundColor = [UIColor clearColor];
    self.clipsToBounds = NO;

    // ... various image views and labels ...

    UIButton *touchArea = [UIButton buttonWithType: UIButtonTypeCustom];
    touchArea.backgroundColor = [UIColor colorWithRed: 1 green: 0 blue: 0 alpha: .3]; // so I can see the bounds
    CGRect touchAreaFrame = self.bounds;
    CGFloat checkboxHitTargetExtension = 7;
    touchAreaFrame.origin.y -= checkboxHitTargetExtension;
    touchAreaFrame.size.height += (checkboxHitTargetExtension * 2);
    touchArea.frame = touchAreaFrame;
    [self addSubview: touchArea];

    // ... add listeners etc ...
  }
  return self;
}

2 个答案:

答案 0 :(得分:2)

您可以使用pointInside:withEvent:来定义特定点是否在视图“内部”。有关详细信息,请参阅UIView参考。

http://developer.apple.com/library/ios/#documentation/uikit/reference/UIView_Class/UIView/UIView.html

同时结帐CGRectOffset非常方便使CGRect更大。

答案 1 :(得分:0)

使按钮不是视图的子项,而是视图的兄弟,并且位于视图的顶部,然后按钮的触摸没有剪切问题。