2012-04-30 236 views
39

我有几个文本输入,每当我触摸背景时我都可以隐藏键盘,但只有当我输入第一个文本框名称textField1时才会隐藏键盘。现在这个代码应该很简单,但我似乎无法得到它,我做错了什么?隐藏键盘ios

-(IBAction)backgroundTouched:(id)sender { 
[textField1 resignFirstResponder]; 
[buildLength resignFirstResponder]; 
[buildWidth resignFirstResponder]; 
[ridgeWidth resignFirstResponder]; 
[rafterWidth resignFirstResponder]; 
[hipWidth resignFirstResponder]; 
[eaveOverhang resignFirstResponder]; 
[spacing resignFirstResponder]; 

}

+0

什么对象正在接受'backgroundTouched:'行动?这是观点吗?你把一切东西放在背后?在iOS上隐藏键盘的方式是覆盖ViewController的'touchesEnded:withEvent:'。它在没有其他对象能够处理触摸事件时被调用。在那里我辞去了第一个响应者,但是你需要检查'isFirstResponder',因为如果你没有使用触摸,你应该调用super。 – Russ

+0

同意@Ru​​ss ...视图控制器上的触摸事件是更简单的方法。但是如果它适用于textField1,它仍然很神秘。为什么不是其他人?我的猜测是其他句柄不好(例如'buildLength'未正确初始化)。 – danh

回答

2

你可以试试UITouch方法,并在此设置你的文本字段对象,并调用resignFirstResponder 当过你的屏幕上的键盘将辞职对碰,我希望这会为你工作。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    [currentSelectedTextField resignFirstResponder]; 
} 
186

如果要隐藏键盘,当你点击一个按钮,你在你view不止一个UITextFields,那么你应该使用:

[self.view endEditing:YES]; 

点击任意位置上来看,和键盘将消失。

+0

我注意到,在某些情况下,此方法在延迟约0.3秒后才起作用。我的意思是,resignFirstResponder立即删除键盘。但是这个方法不行,你应该在使用this之后延迟使用performSelector。 – wzbozon

6

您也可以通过意见阵列(比如你的UIView的子视图)迭代和手动辞职的键盘,如果你不想辞职对你父母的UIView内的所有子视图这是件好事。

- (void)viewDidLoad 
{ 
    self.view.userInteractionEnabled = TRUE; 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
} 

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 
    //Iterate through your subviews, or some other custom array of views 
    for (UIView *view in self.view.subviews) 
     [view resignFirstResponder]; 
} 
27

试试这个:

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    [[self view] endEditing:YES]; 
}