[英]Hide keyboard by touching the screen
我想通過觸摸視圖來隱藏鍵盤。 每個人都建議使用此方法,說不需要鏈接或其他任何操作,但是不起作用。
問題是我的方法沒有被調用,還有其他需要做的事情嗎?
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[[self view] endEditing:YES];
}
我對此有麻煩,因此請使用一種遍歷所有視圖的方法,以查看它們是否為textviews和firstResponders。 不確定UITextView的結構,但是您可能也需要檢查它,盡管它可能已經涵蓋了。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for (UIView *txt in self.view.subviews){
if ([txt isKindOfClass:[UITextField class]] && [txt isFirstResponder]) {
[txt resignFirstResponder];
}
}
}
最好的方法是創建一個“鎖定視圖”,它是一個UIView,一旦textField成為FirstResponder,它將接管整個屏幕。 確保它位於所有視圖的頂部(當然,除了textview之外)。
- (void)loadLockView {
CGRect bounds = [UIScreen mainScreen].bounds;
_lockView = [[UIView alloc] initWithFrame:bounds];
_lockView.backgroundColor = [UIColor clearColor];
UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lockViewTapped:)];
[_lockView addGestureRecognizer:tgr];
[self.view addSubview:_lockView];
}
- (void)lockViewTapped:(UITapGestureRecognizer *)tgr {
[_lockView removeFromSuperView];
[_textField resignFirstResponder];
}
使用UITapGestureRecognizer來關閉鍵盤。
將此代碼寫在您的viewdidload()上。
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(dismissKeyboard)];[self.view addGestureRecognizer:tap];
並在dismissKeyboard方法中放置此代碼。
-(void)dismissKeyboard
{
[TextFieldName resignFirstResponder];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.