【发布时间】:2015-04-13 05:30:03
【问题描述】:
我想通过触摸视图来隐藏键盘。大家都推荐用这个方法,说不用链接什么的,但是不行。
问题是我的方法没有被调用,还有什么需要做的吗?
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[[self view] endEditing:YES];
}
【问题讨论】:
标签: ios uiview keyboard uitouch
我想通过触摸视图来隐藏键盘。大家都推荐用这个方法,说不用链接什么的,但是不行。
问题是我的方法没有被调用,还有什么需要做的吗?
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[[self view] endEditing:YES];
}
【问题讨论】:
标签: ios uiview keyboard uitouch
我遇到了这个问题,所以使用一种方法来遍历所有视图,看看它们是否是 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];
}
}
}
【讨论】:
使用 UITapGestureRecognizer 来关闭键盘。
在你的 viewdidload() 上写下这段代码。
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(dismissKeyboard)];[self.view addGestureRecognizer:tap];
并在dismissKeyboard方法中放置这段代码。
-(void)dismissKeyboard
{
[TextFieldName 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];
}
【讨论】: