问题
I'm writing an app for tvOS - and it all works until I put a UIButton on the screen. The problem, when buttons are added, is that touchesBegan and touchesMoved stop working. If I remove the buttons then touchesBegan and touchesMoved start working correctly again. I have tried, in the interests of experimentation, unchecking 'User Interaction Enabled' - but this didn't make any difference. I have also tried subclassing UIButton and adding the following code:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
[self.nextResponder touchesBegan:touches withEvent:event];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesMoved:touches withEvent:event];
[self.nextResponder touchesMoved:touches withEvent:event];
}
Sadly this doesn't seem to work either. Does anyone have any suggestions as to what I might try next?
回答1:
According to this answer, the button becomes a focused view and it's getting all the touches. You have to make your view (in which you implement touchesBegan
and touchesMoved
) focusable.
回答2:
If the focus engine is used (for instance when you have a UITabbarController
or any UIButton
on the screen) the touch events such as touchesBegan: withEvent:
are indeed no longer called. If you really need them you must first make your view focusable by overriding its readonly property canBecomeFocused
:
- (BOOL)canBecomeFocused {
return YES;
}
Now the focus can be moved to your view and touch events will be triggered as long as it is in focus. However focus may be immediately lost again as it moves along to other focusable items on the screen.
To prevent this, implement on your view:
- (BOOL)shouldUpdateFocusInContext:(UIFocusUpdateContext *)context {
return NO;
}
Now your view can no longer lose its focus. This also means the user can no longer access other focusable items on the screen, so you may need implement logic that allows the user to leave again, for instance a button press.
来源:https://stackoverflow.com/questions/36484115/uibutton-blocking-touchesbegan-and-touchesmoved