簡體   English   中英

同級子視圖在iPhone中不接收觸摸

[英]Sibling subview does not receive touches in iPhone

我有一個視圖( parent與兩個子視圖,一個在頂部() topChild其它的)( bottomChild )。

如果我在屏幕上點擊,只有topChildparent會收到觸摸事件。

我還應該更改什么以將touch事件傳播到bottomChild

編碼:

- (void)viewDidLoad
{
    [super viewDidLoad];
    MYView* parent = [[MYView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    parent.tag = 3;
    parent.backgroundColor = [UIColor redColor];

    MYView* bottomChild = [[MYView alloc] initWithFrame:CGRectMake(0, 0, 90, 90)];
    bottomChild.tag = 2;
    bottomChild.backgroundColor = [UIColor blueColor];
    [parent addSubview:bottomChild];

    MYView* topChild = [[MYView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
    topChild.tag = 1;
    topChild.backgroundColor = [UIColor greenColor];
    [parent addSubview:topChild];
    [self.view addSubview:parent];
}

其中MYViewUIView的子類,僅記錄touchesBegan

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"%d", self.tag);
    [super touchesBegan:touches withEvent:event];
}

結果:

在此處輸入圖片說明

觸摸綠色區域將產生以下日志:

TouchTest[25062:f803] 1
TouchTest[25062:f803] 3

我的第一個想法是讓parent touchesSomething將所有touchesSomething調用傳播給它的子touchesSomething ,但是(A)我懷疑這可能是一個更簡單的解決方案,並且(B)我不知道哪個孩子將事件發送給父touchesSomething ,並向其發送兩次touchesSomething消息同樣的觀點可能會導致惡作劇。

問完問題 ,我發現了這篇文章建議改寫hitTest來更改接收觸摸的視圖。 我將嘗試這種方法並更新問題(如果可行)。

這是一個有趣的問題,可能是通過重新思考事物的結構方式來最好地解決的。 但是要使其按照您建議的方式工作,您需要在當前頂視圖中捕獲touch事件,將其傳遞給父視圖,然后將其向下傳播到父視圖的所有子視圖。 為了完成這項工作,您需要touchesBegan:或您用來攔截觸摸的任何其他方法)在所有視圖中不執行任何操作,僅在父視圖調用的方法中執行操作。

這實際上是另一種說法,即不處理視圖中的觸摸,捕獲它們,但通知父視圖視圖,然后根據需要調用子視圖方法以產生所需的效果。

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    // Do nothing, parent view calls my parentNotifiedTouchesBegan method
    [self.superview touchesBegan:touches withEvent:event];
}

- (void) parentNotifiedTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    // Act on the touch here just as my sibling views are doing
}

注意,我在該代碼self.superview super更改為self.superview 您可能會也可能不想調用super的方法,具體取決於您正在執行的操作以及在parentNotifiedTouchesBegan調用位置。

您當然可以知道哪個subView發送了該事件,只需使用自定義方法來通知超級視圖,而不是調用其touchesBegan: 使用self變量。

如果您不需要撫摸孩子,請設置

bottomChild.userInteractionEnabled = NO;
topChild.userInteractionEnabled = NO;

暫無
暫無

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

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