2012-09-01 26 views
1

我有UITableView上的UITextField,我正在使用數字鍵盤,但是我希望它在用戶單擊除UiTextField之外的任何其他選項時被解除。最優雅的方式來解除UiTableView上的UITextField的數字鍵盤

我已經看到了幾種解決方案,但似乎沒有一個確定的答案。例如有的談的手勢,當我執行他們,他們不會出現使用下面的代碼工作:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 

    [[self view] endEditing:TRUE]; 

} 

正如你可以看到,我想,但沒有,這似乎是工作的一種方式。有人可以引導我嗎?

感謝

+1

關鍵是要送'resignFirstResponder'取其控制是目前第一個響應者幫助(即你的UITextField)。 –

回答

3

通常情況下,你會想打測試反對該不該取消鍵盤區域的觸摸;但總的來說,要求是告訴當前的對焦控制器將其狀態「退出」爲「firstResponder」。這可能是這樣的:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
[self.userInput resignFirstResponder]; 
} 

但是,您可能還需要考慮這個特殊的手勢識別,讓你不必過度分析的NSSet接觸的,從長遠來看(代表對GestureRecognizer確定實際的「解僱認罪!」水龍頭和一個「我可以滾動嗎?」刷卡之差的任務。

+0

當我使用這段代碼時沒有任何反應。 – jini

+0

我相信UiTableViewController不接受觸摸:S – jini

3

您應該使用resignFirstResponder代替:

[textField resignFirstResponder]; 
2

使用下面的代碼

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 
    UITouch *touch = [[event allTouches] anyObject]; 
    // Note the '!': 
    if(![[touch view] class] isKindOfClass [UITableViewController class]]){ 
    // It's not a bubble they touched, dismiss the keyboard: 
    [self.view endEditing:YES]; 
    } 
    [super touchesBegan:touches withEvent:event]; 
} 

否則

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 
    UITouch *touch = [[event allTouches] anyObject]; 
    // Note the '!': 
    if(![[touch view] class] isKindOfClass [UITableViewController class]]){ 
    // It's not a bubble they touched, dismiss the keyboard: 
    [textField resignFirstResponder]; 

    } 
    [super touchesBegan:touches withEvent:event]; 
} 

這個做你想要什麼