使用 UITapGestureRecognizer 使键盘隐藏,当我在 UIButton 内触摸时它不起作用 [重复]
Posted
技术标签:
【中文标题】使用 UITapGestureRecognizer 使键盘隐藏,当我在 UIButton 内触摸时它不起作用 [重复]【英文标题】:Using a UITapGestureRecognizer to make keyboard hides, it doesn't work when I touch inside a UIButton [duplicate] 【发布时间】:2013-09-30 08:22:24 【问题描述】:我已经在我的头文件中声明了这个:
UITapGestureRecognizer* tap;
在viewDidLoad
:
- (void)viewDidLoad
[super viewDidLoad];
// Do any additional setup after loading the view.
tap = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(hideKeyboard)];
tap.enabled = NO;
[self.view addGestureRecognizer:tap];
我添加了UITextFieldDelegate
,并添加了这个:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
tap.enabled = YES;
return YES;
如果我触摸键盘以外的任何地方,它就会消失,但如果我触摸UIButton
,它不会消失。
你知道为什么吗?
【问题讨论】:
看看this 【参考方案1】:UIButton 拦截并处理触摸(不传播它)。一种选择是将您的视图控制器设置为手势识别器委托并实现该方法:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
但在您的情况下,我认为在按下按钮时触发的方法中关闭键盘就足够了。
【讨论】:
【参考方案2】: UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
tapGestureRecognizer.delegate = self;
tapGestureRecognizer.numberOfTapsRequired = 1;
[self.view addGestureRecognizer:tapGestureRecognizer];
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
if (touch.view == self.button) //change it to your condition UIButton
return NO;
return YES;
-(void)dismissKeyboard
[self.textField resignFirstResponder];
【讨论】:
【参考方案3】:为用户按下按钮时添加目标-动作配对:
[button addTarget:self
action:@selector(dismissKeyboard)
forControlEvents:UIControlEventTouchDown];
【讨论】:
以上是关于使用 UITapGestureRecognizer 使键盘隐藏,当我在 UIButton 内触摸时它不起作用 [重复]的主要内容,如果未能解决你的问题,请参考以下文章
在 Swift 中使用 UITapGestureRecognizer 中的参数
使用 UITapGestureRecognizer 时不会调用 textFieldShouldEndEditing