当用户按下其他控件/空格时,如何取消聚焦 UITextFields? [英] How do I unfocus UITextFields when user presses other controls/blank space?

查看:24
本文介绍了当用户按下其他控件/空格时,如何取消聚焦 UITextFields?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UITextField.它正常工作,这意味着当按下时,它会触发 EditingDidBegin 方法等.问题是我无法取消选择它,这意味着键盘将始终可见,覆盖重要的控件.我认为当用户点击与 UITextField 不同的地方时,默认行为是取消选择/隐藏键盘,例如在它周围的空白处,但它不是 - UITextField 是还在那儿.实现此行为的一种选择是向 UITextFields 以外的所有内容添加触摸侦听器,并在触发时手动取消对焦,但由于显而易见的原因,这将是一个糟糕的解决方案.

I have a UITextField. It works normally, meaning that when pressed, it fires EditingDidBegin method etc. The problem is that I cannot deselect it, meaning that the keyboard will be always visible, covering important controls. I thought that default behavior would be deselecting/hiding keyboard when user clicks somewhere different from the UITextField, for example on the empty space around it, but it's not - the UITextField is still there. One option to achieve this behavior would be adding touch listener to everything other than UITextFields and perform manual unfocusing when it fires, but that would be a terrible solution for obvious reasons.

问题是,当用户按下其他控件/空白"时,我如何取消聚焦 UITextFields?

Question is, how do I unfocus UITextFields when user presses other controls/"blank space"?

建议的选项不适用于我需要的 Xamarin.iOS.

推荐答案

我总是把这个添加到我的 ViewController

I always add this to my ViewController

override func viewDidLoad()
{
    super.viewDidLoad()

    // other stuff

    // but to stop editing when the user taps anywhere on the view, add this gesture recogniser
    let tapGestureBackground = UITapGestureRecognizer(target: self, action: #selector(self.backgroundTapped(_:)))
    self.view.addGestureRecognizer(tapGestureBackground)
}

func backgroundTapped(_ sender: UITapGestureRecognizer)
{
    self.endEditing(true)   
}

这篇关于当用户按下其他控件/空格时,如何取消聚焦 UITextFields?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆