0

我在我的头文件中声明了这个:

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;
}

如果我触摸键盘外的任何地方,它就会消失,但如果我触摸 aUIButton它不会消失。

你知道为什么吗?

4

3 回答 3

0

UIButton 拦截并处理触摸(不传播它)。一种选择是将您的视图控制器设置为手势识别器委托并实现该方法:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch

但在你的情况下,我认为在按下按钮时触发的方法中关闭键盘就足够了。

于 2013-09-30T08:36:03.900 回答
0
 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];
}
于 2013-09-30T08:37:48.030 回答
0

为用户按下按钮时添加目标-动作配对:

[button addTarget:self
           action:@selector(dismissKeyboard)
 forControlEvents:UIControlEventTouchDown];
于 2013-09-30T08:44:16.157 回答