触摸UITextField外的任何地方时如何解除键盘(在swift中)?

时间:2015-08-29 00:55:32

标签: ios swift uitextfield uikeyboard

我正在开发一个具有UIViewController的项目,在视图控制器上,在scrollview上有一个UIScrollView和一个UITextField。 像这样: 我正试图解除键盘并在文本字段中键入一些文本后隐藏它并点击文本字段外的任何位置。 我尝试过以下代码:

override func viewDidLoad() {
    super.viewDidLoad()
    self.textField.delegate = self;
}

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

当我点击滚动视图外,它对我有用,但是当我点击滚动视图时,没有任何反应,键盘也不会隐藏。

在文本字段外点击任何地方时,有没有办法解雇键盘? 感谢

19 个答案:

答案 0 :(得分:101)

为Swift 4编辑

修改:已添加@objc。虽然这不是性能的最佳选择,但在有更好的解决方案之前,这里的一个实例不应该导致太多问题。

修改时需要与GestureRecognizer背后的项目进行互动。

编辑:感谢@Rao指出这一点。添加了tap.cancelsTouchesInView = false

这可以帮助您拥有多个UITextViewUITextField

创建视图控制器的扩展。这对我来说更顺畅,而且比试图使用.resignFirstResponder()

更麻烦
extension UIViewController
{
    func hideKeyboard()
    {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(
            target: self,
            action: #selector(UIViewController.dismissKeyboard))

        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

    @objc func dismissKeyboard()
    {
        view.endEditing(true)
    }
}

在viewDidLoad

中调用self.hideKeyboard()

答案 1 :(得分:56)

试试这个,经过测试和运作:

适用于Swift 3.0 / 4.0

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

适用于较旧的Swift

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

答案 2 :(得分:14)

swift 3

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))
}

答案 3 :(得分:13)

在这种情况下,有UITapGesture作为选择之一。为了以防万一,我尝试创建示例代码。像这样,

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var scrollView: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let tapGesture = UITapGestureRecognizer(target: self, action: "tap:")
        view.addGestureRecognizer(tapGesture)
    }

    func tap(gesture: UITapGestureRecognizer) {
        textField.resignFirstResponder()
    }
}

答案 4 :(得分:11)

适用于ScrollView的Swift 3工作解决方案

dummies <- cbind(qdapTools::mtabulate(Religion), Religion)

另一个question谈论我引用和使用的这个问题。接受的答案在Swift 3中不再有效。当前选择的答案应该是以下答案。

答案 5 :(得分:5)

详细

  • Xcode 10.2.1(10E1001),Swift 5

解决方案1 ​​

endEditing(_:)

let gesture = UITapGestureRecognizer(target: tableView, action: #selector(UITextView.endEditing(_:)))
tableView.addGestureRecognizer(gesture)

溶液的使用1.完整样品

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let textField = UITextField(frame: CGRect(x: 50, y: 50, width: 200, height: 30))
        textField.borderStyle = .roundedRect
        textField.placeholder = "Enter text"
        textField.becomeFirstResponder()
        view.addSubview(textField)
        let gesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:)))
        view.addGestureRecognizer(gesture)
    }
}

解决方案2

  

类TapGestureRecognizer

import UIKit

class TapGestureRecognizer: UITapGestureRecognizer {

    let identifier: String

    init(target: Any?, action: Selector?, identifier: String) {
        self.identifier = identifier
        super.init(target: target, action: action)
    }

    static func == (left: TapGestureRecognizer, right: TapGestureRecognizer) -> Bool {
        return left.identifier == right.identifier
    }
}
  

扩展名UIView

import UIKit

extension UIView {

    private var hideKeybordOnTapIdentifier: String { return "hideKeybordOnTapIdentifier" }

    private var hideKeybordOnTapGestureRecognizer: TapGestureRecognizer? {
        let hideKeyboardGesture = TapGestureRecognizer(target: self, action: #selector(UIView.hideKeyboard),
                                                       identifier: hideKeybordOnTapIdentifier)
        if let gestureRecognizers = self.gestureRecognizers {
            for gestureRecognizer in gestureRecognizers {
                if let tapGestureRecognizer = gestureRecognizer as? TapGestureRecognizer,
                    tapGestureRecognizer == hideKeyboardGesture {
                    return tapGestureRecognizer
                }
            }
        }
        return nil
    }

    @objc private func hideKeyboard() { endEditing(true) }

    var hideKeyboardOnTap: Bool {
        set {
            let hideKeyboardGesture = TapGestureRecognizer(target: self, action: #selector(hideKeyboard),
                                                           identifier: hideKeybordOnTapIdentifier)
            if let hideKeybordOnTapGestureRecognizer = hideKeybordOnTapGestureRecognizer {
                removeGestureRecognizer(hideKeybordOnTapGestureRecognizer)
                if gestureRecognizers?.count == 0 { gestureRecognizers = nil }
            }
            if newValue { addGestureRecognizer(hideKeyboardGesture) }
        }
        get { return hideKeybordOnTapGestureRecognizer == nil ? false : true }
    }
}

溶液2的使用

view.hideKeyboardOnTap = true

解决方案2完整样本

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let textField = UITextField(frame: CGRect(x: 50, y: 50, width: 200, height: 30))
        textField.borderStyle = .roundedRect
        textField.placeholder = "Enter text"
        textField.becomeFirstResponder()
        view.addSubview(textField)
        view.hideKeyboardOnTap = true
    }
}

答案 6 :(得分:5)

检查一下。

{{1}}

然后你的点击处理程序是。

{{1}}

答案 7 :(得分:3)

对于Swift 3

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

答案 8 :(得分:2)

当在输入区域外触摸任意数量的输入项目时,此功能正常工作。

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

答案 9 :(得分:1)

我有同样的问题,我终于解决了!

在Storyboard中设置TapGestureRecognizer,然后在ViewController中设置Outlet

@IBOutlet var tapGesture: UITapGestureRecognizer!

然后在ViewController中设置IBAction

@IBAction func DismissKeyboard(sender: UITapGestureRecognizer)
{
 self.view.endEditing(true)
} 

将这些行添加到viewDidLoad方法

override func viewDidLoad()
{
    super.viewDidLoad()
    self.view.addGestureRecognizer(tapGesture)
}

它应该工作

希望这会有所帮助!

答案 10 :(得分:1)

每次触摸不同的文字字段都会关闭键盘或使用resignfirstresponder

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
 UITouch *touch = [touches anyObject];
 if(![touch.view isMemberOfClass:[UITextField class]]) {
     [touch.view endEditing:YES];
 }
}

答案 11 :(得分:1)

func findAndResignFirstResponder(_ stView: UIView) -> Bool {

    if stView.isFirstResponder {
        stView.resignFirstResponder()
        return true
    }
    for subView: UIView in stView.subviews {
        if findAndResignFirstResponder(subView) {
            return true
        }
    }
    return false
}

答案 12 :(得分:0)

我在Swift 4中使用了以下代码,您可以尝试一下

override func viewDidLoad() {
    super.viewDidLoad()

    // dismiss keyboard when tap outside a text field 
    let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(YourViewControllerName.dismissKeyboard))
    view.addGestureRecognizer(tapGestureRecognizer)
}

//Calls this function when the tap is recognized.
func dismissKeyboard() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    view.endEditing(true)
}

答案 13 :(得分:0)

在Swift 4或5中,您可以使用like ..

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    //Key borad dismiss
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
    tap.cancelsTouchesInView = false
    view.addGestureRecognizer(tap)
  }

 //Key board hide on outside the textfield
 @objc func dismissKeyboard() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    view.endEditing(true)
  }
}

答案 14 :(得分:0)

在Swift4中

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

答案 15 :(得分:0)

//迅速4.对我有用。

func setupKeyboardDismissRecognizer(){
    let tapRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(searchingActivity.dismissKeyboard))

    self.view.addGestureRecognizer(tapRecognizer)
}

    @objc func dismissKeyboard()
    {
        view.endEditing(true)
        searchTableView.isHidden = true
    }

///在viewDidLoad中调用此函数setupKeyboardDismissRecognizer()

答案 16 :(得分:0)

引入点击手势识别器并为其设置和操作。

使用代码:

nameofyourtextfield .resignfirstresponder()

答案 17 :(得分:0)

转到“键盘类型”并选择“默认”或任何您需要TextField的内容。然后覆盖一个方法,无论你想要什么,我通常称之为touchBegins。以下是您忘记添加的内容

super.touchingBegins(touches, withEvent: event)
 }

答案 18 :(得分:0)

我在Obj-C中创建了这个方法,无论用户当前在哪里键入,它都会隐藏键盘:

//call this method
+ (void)hideKeyboard {
    //grab the main window of the application
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    //call our recursive method below
    [self resignResponderForView:window];
}

//our recursive method
+ (void)resignResponderForView:(UIView *)view {
    //resign responder from this view
    //If it has the keyboard, then it will hide the keyboard
    [view resignFirstResponder];
    //if it has no subviews, then return back up the stack
    if (view.subviews.count == 0)
        return;
    //go through all of its subviews
    for (UIView *subview in view.subviews) {
        //recursively call the method on those subviews
        [self resignResponderForView:subview];
    }
}

我希望这可以转化为Swift并且有意义。它可以在应用程序的任何地方调用,无论你使用什么VC或任何东西,它都会隐藏键盘。