Подтвердить что ты не робот

Как убрать клавиатуру при касании где-либо вне UITextField (в быстром)?

Я работаю над проектом с UIViewController, на контроллере представления есть UIScrollView и UITextField в scrollview. как это: Я пытаюсь убрать клавиатуру и скрыть ее, набрав текст в текстовом поле и коснуться любого места вне текстового поля. Я пробовал следующий код:

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

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

Он работает для меня, когда я выхожу за пределы scrollview, но когда я нажимаю на прокрутку, ничего не происходит, и клавиатура не скрывается.

Есть ли способ отклонить клавиатуру при нажатии в любом месте вне текстового поля? спасибо

4b9b3361

Ответ 1

Отредактировано для Swift 4

Редактировать: Добавлено @objc. Хотя это не лучший вариант для повышения производительности, один его пример не должен вызывать слишком много проблем, пока не будет найдено лучшее решение.

Отредактировано, чтобы исправить, когда нужно взаимодействовать с элементами позади GestureRecognizer.

Редактировать: Спасибо @Rao за указание на это. Добавлен tap.cancelsTouchesInView = false.

Это должно помочь вам с несколькими UITextView или UITextField

Создайте расширение контроллера представления. Для меня это сработало намного проще и с меньшими хлопотами, чем попытка использовать .resignFirstResponder()

extension UIViewController
{
    func setupToHideKeyboardOnTapOnView()
    {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(
            target: self,
            action: #selector(UIViewController.dismissKeyboard))

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

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

Звоните self.setupToHideKeyboardOnTapOnView() в viewDidLoad

Ответ 2

Попробуйте это, он протестирован и работает:

Для 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)
}

Ответ 3

swift 3

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

Ответ 4

В этом случае 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()
    }
}

Ответ 5

Рабочее решение для Swift 3, которое работает с ScrollView

class ViewController: UIViewController {

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

    override func viewDidLoad() {
        super.viewDidLoad()

        // The next line is the crucial part
        // The action is where Swift 3 varies from previous versions
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tap(gesture:)))
        self.view.addGestureRecognizer(tapGesture)
    }

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

Другой question, который говорит об этой проблеме, на которую я ссылался и использовал. Принимаемый ответ больше не работает в Swift 3. Текущий выбранный ответ должен быть ниже.

Ответ 6

Подробнее

  • 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
    }
}

Ответ 7

Проверьте это.

override func viewDidLoad() {
    var tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleTap))
    self.view.userInteractionEnabled = true
    self.view.addGestureRecognizer(tapGesture)
}

Тогда ваш обработчик крана.

  func handleTap(sender: UITapGestureRecognizer) {
    self.view.endEditing(true)
}

Ответ 8

Для Swift 3

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

Ответ 9

Это срабатывает при касании внешней области ввода для любого количества элементов ввода.

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

Ответ 10

У меня была та же проблема, и я, наконец, решил ее!

Установите TapGestureRecognizer в своей раскадровке, а затем выйдите в свой ViewController

@IBOutlet var tapGesture: UITapGestureRecognizer!

Затем установите IBAction в вашем ViewController

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

добавьте эти строки в свой метод viewDidLoad

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

и его работа должна

Надеюсь, что это поможет!

Ответ 11

Каждое касание, отличное от текстового поля, отбрасывает клавиатуру или использует resignfirstresponder

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

Ответ 12

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
}

Ответ 13

Я создал этот метод в 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 вы находитесь или что-то в этом роде.

Ответ 14

Перейдите в "Тип клавиатуры" и выберите "По умолчанию" или что вам нужно для TextField. Затем переопределите метод, назовите его, как хотите, я обычно называю его touchingBegins. Ниже вы забыли добавить

super.touchingBegins(touches, withEvent: event)
 }

Ответ 15

Ввести признак распознавания жестов, а также установить и принять меры для него.

Используйте код:

nameofyourtextfield.resignfirstresponder()

Ответ 16

//Свифт 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
    }

//Вызываем эту функцию setupKeyboardDismissRecognizer() в viewDidLoad

Ответ 17

В Swift4

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

Ответ 18

В Swift 4 или 5 можно использовать как.

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)
  }
}