当我将手势添加到 的子类时UIScrollView
,我遇到了视图树中的各种手势相互干扰的问题,例如能够单击子视图、滚动视图以及在所有情况下都关闭键盘。我想出了这个解决方案,它可以从超类UIScrollView
或UIViewController
.
该类DismissKeyboardTapGesture
使用 ARC,适用于视图下的任何文本字段,并且不会接管来自按钮等子视图的任何点击。还利用 iOS7 滚动效果来关闭键盘。
从 UISScrollView 超类设置:
_dismissKeyboard = [[DismissKeyboardTapGesture alloc] initWithView:self];
或来自 UIViewController:
_dismissKeyboard = [[DismissKeyboardTapGesture alloc] initWithView:self.view];
这是课程:
@interface DismissKeyboardTapGesture : NSObject <UIGestureRecognizerDelegate>
@end
@implementation DismissKeyboardTapGesture
- (id)initWithView:(UIView *)view
{
self = [super init];
if (self) {
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
singleTap.cancelsTouchesInView = NO;
singleTap.delegate = self;
[view addGestureRecognizer:singleTap];
if ([view respondsToSelector:@selector(setKeyboardDismissMode:)]) {
// Bonus effect to dismiss keyboard by scrolling
((UIScrollView *)view).keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;
}
}
return self;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
// Don't stop any existing gestures in our view from working
if (otherGestureRecognizer.view == gestureRecognizer.view) {
return YES;
}
return NO;
}
- (void)singleTap:(UIGestureRecognizer*)gestureRecognizer
{
// Close keyboard for any text edit views that are children of the main view
[gestureRecognizer.view endEditing:YES];
}
@end