簡體   English   中英

如何使未剪輯的子視圖接收觸摸事件?

[英]How can I make an unclipped subview receive touch events?

我有一個小的自定義視圖,我用作按鈕。 我使用一個簡單的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;
}

您可以使用pointInside:withEvent:來定義特定點是否在視圖“內部”。 有關詳細信息,請參閱UIView參考。

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

結帳CGRectOffset非常方便使CGRect更大。

使按鈕不是視圖的子項,而是視圖的兄弟,並且位於它的頂部,然后按鈕的觸摸沒有剪切問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM