ios 当用户点击其他地方时如何从文本字段中退出第一响应者?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7794959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:53:57  来源:igfitidea点击:

How to resign first responder from text field when user tap elsewhere?

iphoneiosios4uiscrollviewuitextfield

提问by Steve

I have filled my view with ScrollView (same size as the view) and I'm stuck at how to resign first responder when user tap elsewhere in the View (or the scrollview). Any idea on how to do that ? I'm using the following method but it's not working as expected:

我已经用 ScrollView(与视图大小相同)填充了我的视图,并且当用户点击视图(或滚动视图)中的其他地方时,我被困在如何退出第一响应者。关于如何做到这一点的任何想法?我正在使用以下方法,但没有按预期工作:

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

Thx for helping,

感谢帮助,

Stephane

斯蒂芬

回答by DanSkeel

I found an answer here: link

我在这里找到了答案:链接

If your ultimate aim is just to resign the first responder, this should work: [self.view endEditing:YES]

如果你的最终目标只是让第一响应者辞职,这应该有效:[self.view endEditing:YES]

This method is designed right for it! Reference: endEditing:

这种方法是为它设计的!参考:结束编辑:

Causes the view (or one of its embedded text fields) to resign the first responder status.

导致视图(或其嵌入的文本字段之一)放弃第一响应者状态。

回答by Andres Canella

For a more robust and clean solution add a tap gesture recognizer to your primary view.

要获得更强大、更干净的解决方案,请在主视图中添加点击手势识别器。

This will work better with nested views and will be cleaner than secret buttons in code and UI builder.

这将更好地与嵌套视图一起使用,并且比代码和 UI 构建器中的秘密按钮更干净。

In your view did load:

在您看来,确实加载了:

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

..and define your target action to be triggered on tap:

..并定义要在点击时触发的目标操作:

-(void) dismissKeyboard:(id)sender
{
    [self.view endEditing:YES];
}

回答by pableiros

For Swift 3and Swift 4you can do this:

对于Swift 3Swift 4,您可以这样做:

func viewDidLoad() {
    super.viewDidLoad()

    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.hideKeyboardByTappingOutside))

    self.view.addGestureRecognizer(tap)
}

@objc func hideKeyboardByTappingOutside() {
    self.view.endEditing(true)
}

回答by Onder OZCAN

The best option is the shortest way ;)

最好的选择是最短的方法;)

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

回答by nacho4d

UIViewControllerinherits from UIResponderso a naive way (I am pretty sure is not the smartest way to do it) would be by overwriting the following methods (at least 1 of them)

UIViewController继承自UIResponder如此幼稚的方式(我很确定这不是最聪明的方法)是通过覆盖以下方法(至少其中一种)

– touchesBegan:withEvent:
– touchesMoved:withEvent:
– touchesEnded:withEvent:
- touchesCancelled:withEvent:

Next you could get the touched view by doing

接下来你可以通过做得到触摸视图

UITouch *touch = [touches anyObject];
UIView *touchedView = [touch view];

finally resign the first responder if that view is not your text field

如果该视图不是您的文本字段,则最终辞去第一响应者的职务

if(touchedView != textField){
    [textField resignFirstResponder];
}

_

_

Demerits of this approach:

这种方法的缺点:

You will have to handle the "tap" by yourself. (Same problem as the old iOS 3.1 or earlier). You will have to come up with your own implementation to differentiate single taps from drags, swipes, double taps, long taps, etc. Is not hard to get it working well but it is not likely you get it exactly the same way Apple detects taps (timings, distances, thresholds count!) However, that depends on your needs.

您将不得不自己处理“水龙头”。(与旧的 iOS 3.1 或更早版本的问题相同)。您将不得不想出自己的实现来区分单击与拖动、滑动、双击、长按等。 让它正常工作并不难,但您不太可能以与 Apple 检测点击的方式完全相同的方式获得它(时间、距离、阈值很重要!)但是,这取决于您的需求。

If your view structure is simple enough then you could add a gesture recognizer to the container view and resign the first responder every time the handler is called :)

如果您的视图结构足够简单,那么您可以在容器视图中添加一个手势识别器,并在每次调用处理程序时让第一响应者退出:)

Hope this helps

希望这可以帮助

回答by Gavin

Nobody has yet presented the best answer here:

还没有人在这里给出最佳答案:

[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];

From the documentation on this method:

从有关此方法的文档中:

Normally, this method is invoked by a UIControl object that the user has touched. The default implementation dispatches the action method to the given target object or, if no target is specified, to the first responder. Subclasses may override this method to perform special dispatching of action messages.

通常,此方法由用户触摸的 UIControl 对象调用。默认实现将 action 方法分派给给定的目标对象,或者如果没有指定目标,则分派给第一响应者。子类可以覆盖此方法以执行动作消息的特殊调度。

I bolded the relevant part of that paragraph. By specifying nilfor the to:parameter, we automatically call the given selector on the first responder, wherever it is, and we don't need to have any knowledge of where in the view hierarchy it is. This can also be used to invoke other methods on the first responder as well, not just cause it to resign first responder status.

我加粗了该段的相关部分。通过指定nilto:参数,我们会自动调用的第一个响应者给定的选择,无论它是,我们不需要有在那里的视图层次是任何知识。这也可用于在第一响应者上调用其他方法,而不仅仅是使其退出第一响应者状态。

回答by Deepakraj Murugesan

    -(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.TextField resignFirstResponder];

    return YES;
}

回答by Lefteris

Give a unique Tag to your UITextfield (i.e. 333), then to resign the first responder do this:

给你的 UITextfield 一个唯一的标签(即 333),然后辞职第一响应者这样做:

UITextField *textField = (UITextField *)[self.view viewWithTag:333];
[textField resignFirstResponder];

回答by Ghanshyam Tomar

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapTodissmiss)];

[self.view addGestureRecognizer:tap];

and selector

和选择器

-(void)TapTodissmiss{

    [self.txtffld resignFirstResponder];

}

回答by Or Ron

Just create an IBOutletor pointer to the text field and call [textField resignFirstResponder];from where ever you want.

只需创建一个IBOutlet指向文本字段的或 指针,然后[textField resignFirstResponder];从您想要的任何地方调用。