在文本字段外面隐藏键盘

时间:2012-09-01 12:46:51

标签: ios uitextfield uikeyboard

我试图在屏幕上的任何其他位置触摸后隐藏键盘。我正在使用的代码基于this answer

IBOutlet UITextView *myTextView;

方法:

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

    UITouch *touch = [[event allTouches] anyObject];
    if ([myTextView isFirstResponder] && [touch view] != myTextView) {
        [myTextView resignFirstResponder];
    }
    [super touchesBegan:touches withEvent:event];
}

我不明白的是我应该如何将我的UITextField链接到touchesBegan方法。我需要使用哪个发送的事件?此外,该方法不应该是IBAction,因为现在我无法将我的UITextField连接到它。

我还尝试了this code,但是我的导航按钮正在破坏(即使是评论中提到的解决方案)

6 个答案:

答案 0 :(得分:26)

目标C:

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

夫特:

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    self.view.endEditing(true)
}

这是我找到的最好的方式,而且非常简单。

答案 1 :(得分:6)

  

我应该如何将我的UITextField链接到touchesBegan方法。我需要使用哪个发送的事件?此外,该方法不应该是IBAction,因为现在我无法将我的UITextField连接到它。

因为你没有。您必须在文本字段为子视图的视图上覆盖此方法。

答案 2 :(得分:4)

我所做的是将整个UIView类更改为UIControl。 enter image description here

这为您提供了一个touchDown事件,您可以链接到resignFirstResponder的方法。 enter image description here
UIControl仍然为您提供UIView的所有功能。

-(IBAction)backgroundTap:(id)sender
{
    [text1 resignFirstResponder];
    [text2 resignFirstResponder];
    [textLogin resignFirstResponder];
    [textPassword resignFirstResponder];
} // Resign all responders

答案 3 :(得分:0)

- (void)viewDidLoad
{
     //for keybord hide when touch outside:


    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(hidekeybord)];
    [self.view addGestureRecognizer:tap];



    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}


-(void)hidekeybord
{

    [_yourtextfield.txt resignFirstResponder];

}

答案 4 :(得分:0)

In .h
@property (nonatomic, assign) id currentResponder;

In .h
//in viewDidLoad:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignOnTap:)];
    [singleTap setNumberOfTapsRequired:1];
    [singleTap setNumberOfTouchesRequired:1];
    [self.view addGestureRecognizer:singleTap];

//Implement the below delegate method:

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    self.currentResponder = textField;
}

//Implement resignOnTap:

- (void)resignOnTap:(id)iSender {
    [self.currentResponder resignFirstResponder];
}

答案 5 :(得分:-2)

尝试快速而肮脏的方式:

按一个按钮并将其链接到一个动作方法(我们称之为背景)。拉伸按钮使其覆盖整个视图。调整视图的图层,以便只有用户通过触摸进行交互的内容才会位于按钮的顶部。将按钮类型更改为自定义,这使按钮不可见。在方法Background中解除firstResponder。