在你viewDidLoad
方法添加此手勢識別:
UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
gestureRecognizer.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:gestureRecognizer];
然後添加dismissKeyboard
方法:
- (void) dismissKeyboard{
[YOURFIELDHERE resignFirstResponder];
}
您還需要添加這使它這樣的按鈕仍然可點擊,而不是被手勢識別器覆蓋:
gestureRecognizer.delegate = self; // in viewDidLoad
<UIGestureRecognizerDelegate> //in your header file
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
if ([touch.view isKindOfClass:[UIButton class]]){
return NO;
}
return YES; // handle the touch
}
GestureRecognizer的委託是我沒有使用的東西。相反,我使用愚蠢的子類來處理觸摸,這可以做得更容易。謝謝。 – Eugene
我犯了這個錯誤不止一次。重新發明了車輪,並不是那麼優雅,只是發現有一種代表性的方法能夠達到我想要達到的目標,甚至超過了我的成就。在我看來,這是蘋果文檔的真正垮臺。 –
很好的答案!非常感謝你! – HiveHicks