2013-09-30 28 views
0

我在頭文件中聲明裏面不起作用此:一個UITapGestureRecognizer使鍵盤皮,當我觸摸到一個UIButton

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中觸摸它並不會消失。

你知道爲什麼嗎?

+0

看看[這裏](http://stackoverflow.com/questions/3344341/uibutton - 內 - 一 - 視圖 - 即-具有-A-uitapgesturerecognizer) – luiso1979

回答

0

UIButton攔截並處理觸摸(不傳播它)。一種選擇是設置您的視圖控制器作爲手勢識別代表和實現方法:

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

但在你的情況下,我認爲這將是足以解聘的方法觸發該鍵盤在按下按鈕時。

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

添加一個目標 - 動作配對當用戶觸摸向下按鈕:

[button addTarget:self 
      action:@selector(dismissKeyboard) 
forControlEvents:UIControlEventTouchDown];