[英]Sibling subview does not receive touches in iPhone
我有一個視圖( parent
與兩個子視圖,一個在頂部() topChild
其它的)( bottomChild
)。
如果我在屏幕上點擊,只有topChild
和parent
會收到觸摸事件。
我還應該更改什么以將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];
}
其中MYView
是UIView
的子類,僅記錄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
消息同樣的觀點可能會導致惡作劇。
這是一個有趣的問題,可能是通過重新思考事物的結構方式來最好地解決的。 但是要使其按照您建議的方式工作,您需要在當前頂視圖中捕獲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.