Zamknij klawiaturę iOS, dotykając w dowolnym miejscu za pomocą Swift

Szukałem tego wszędzie, ale nie mogę go znaleźć. Wiem jak wyłączyć klawiaturę używając Objective-C ale nie mam pojęcia jak to zrobić używając Swift? Czy ktoś wie?

Author: Sandy, 2014-06-09

30 answers

override func viewDidLoad() {
    super.viewDidLoad()

    //Looks for single or multiple taps. 
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")

    //Uncomment the line below if you want the tap not not interfere and cancel other interactions.
    //tap.cancelsTouchesInView = false 

    view.addGestureRecognizer(tap)
}

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

Oto inny sposób wykonania tego zadania, jeśli zamierzasz korzystać z tej funkcji w wielu UIViewControllers:

// Put this piece of code anywhere you like
extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false            
        view.addGestureRecognizer(tap)
    }

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

Teraz w każdym UIViewController wystarczy wywołać tę funkcję:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround() 
}

Ta funkcja jest dołączona jako standardowa funkcja w moim repo, która zawiera wiele przydatnych rozszerzeń Swift, takich jak ten, sprawdź to: https://github.com/goktugyil/EZSwiftExtensions

 1014
Author: Esqarrouth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-20 19:28:07

ODPOWIEDŹ na twoje pytanie, Jak wyłączyć klawiaturę w Xcode 6.1 za pomocą Swift poniżej:

import UIKit

class ItemViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var textFieldItemName: UITextField!

    @IBOutlet var textFieldQt: UITextField!

    @IBOutlet var textFieldMoreInfo: UITextField!


    override func viewDidLoad() {
        super.viewDidLoad()

        textFieldItemName.delegate = self
        textFieldQt.delegate = self
        textFieldMoreInfo.delegate = self
    }

                       ...

    /**
     * Called when 'return' key pressed. return NO to ignore.
     */
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }


   /**
    * Called when the user click on the view (outside the UITextField).
    */
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.view.endEditing(true)
    }

}

(Źródło tej informacji ).

 97
Author: King-Wizard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-22 07:16:43

Możesz zadzwonić

resignFirstResponder()

Na dowolnej instancji UIResponder, takiej jak UITextField. Jeśli wywołasz go w widoku, który aktualnie powoduje wyświetlenie klawiatury, klawiatura zostanie odrzucona.

 29
Author: Dash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-09 18:42:41
//Simple exercise to demonstrate, assuming the view controller has a //Textfield, Button and a Label. And that the label should display the //userinputs when button clicked. And if you want the keyboard to disappear //when clicken anywhere on the screen + upon clicking Return key in the //keyboard. Dont forget to add "UITextFieldDelegate" and 
//"self.userInput.delegate = self" as below

import UIKit

class ViewController: UIViewController,UITextFieldDelegate {

    @IBOutlet weak var userInput: UITextField!
    @IBAction func transferBtn(sender: AnyObject) {
                display.text = userInput.text

    }
    @IBOutlet weak var display: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

//This is important for the textFieldShouldReturn function, conforming to textfieldDelegate and setting it to self
        self.userInput.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

//This is for the keyboard to GO AWAYY !! when user clicks anywhere on the view
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.view.endEditing(true)
    }


//This is for the keyboard to GO AWAYY !! when user clicks "Return" key  on the keyboard

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

}
 15
Author: Naishta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-16 21:11:50

Dla Swift 3 jest to bardzo proste

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

Jeśli chcesz ukryć klawiaturę po naciśnięciu klawisza RETURN

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

Ale w drugim przypadku będziesz również musiał przekazać delegata ze wszystkich pól tekstowych do kontrolera ViewController w głównym.Storyboard

 15
Author: Yerbol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-26 18:26:56

Swift 3: Najprostszy sposób na usunięcie klawiatury:

  //Dismiss keyboard method
    func keyboardDismiss() {
        textField.resignFirstResponder()
    }

    //ADD Gesture Recignizer to Dismiss keyboard then view tapped
    @IBAction func viewTapped(_ sender: AnyObject) {
        keyboardDismiss()
    }

    //Dismiss keyboard using Return Key (Done) Button
    //Do not forgot to add protocol UITextFieldDelegate 
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        keyboardDismiss()

        return true
    }
 10
Author: NikaE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-15 03:07:04

Swift 4 działa

Utwórz rozszerzenie jak poniżej & wywołaj hideKeyboardWhenTappedAround() w kontrolerze widoku podstawowego.

//
//  UIViewController+Extension.swift
//  Project Name
//
//  Created by ABC on 2/3/18.
//  Copyright © 2018 ABC. All rights reserved.
//

import UIKit

extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tapGesture = UITapGestureRecognizer(target: self, 
                         action: #selector(hideKeyboard))
        view.addGestureRecognizer(tapGesture)
    }

    @objc func hideKeyboard() {
        view.endEditing(true)
    }
}
 10
Author: Fahim Parkar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-18 07:46:40

Odpowiedź Dasha jest prawidłowa i preferowana. Bardziej" spalona Ziemia " podejście jest zadzwonić view.endEditing(true). Powoduje to, że view i wszystkie jego podwidywacze stają się resignFirstResponder. Jeśli nie masz odniesienia do widoku, który chcesz odrzucić, jest to hakerskie, ale skuteczne rozwiązanie.

Zauważ, że osobiście uważam, że powinieneś mieć odniesienie do widoku, który chciałbyś mieć. .endEditing(force: Bool) jest barbarzyńskim podejściem; proszę, nie używaj go.
 9
Author: modocache,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-09 18:52:25

W storyboardzie:

  1. Wybierz widok tabeli
  2. z prawej strony wybierz atrybut Inspektor
  3. w sekcji Klawiatura-wybierz żądany tryb zamykania
 9
Author: goggelj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-30 23:05:37

Swift 3:

Rozszerzenie z Selector jako parametrem, aby móc robić dodatkowe rzeczy w funkcji Odrzuć I cancelsTouchesInView aby zapobiec zniekształceniom z dotknięciami innych elementów widoku.

extension UIViewController {
    func hideKeyboardOnTap(_ selector: Selector) {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: selector)
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }
}

Użycie:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardOnTap(#selector(self.dismissKeyboard))
}

func dismissKeyboard() {
    view.endEditing(true)
    // do aditional stuff
}
 9
Author: David Seek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-07 06:15:19

![jak wyłączyć klawiaturę..][1]

import UIKit

class ViewController: UIViewController,UITextFieldDelegate {

   @IBOutlet weak var username: UITextField!
   @IBOutlet weak var password: UITextField!

   override func viewDidLoad() {
      super.viewDidLoad() 
      username.delegate = self
      password.delegate = self
      // Do any additional setup after loading the view, typically from a nib.
   }

   override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
      // Dispose of any resources that can be recreated.
   }

   func textFieldShouldReturn(textField: UITextField!) -> Bool // called when   'return' key pressed. return NO to ignore.
   {
      textField.resignFirstResponder()
      return true;
   }

   override func touchesBegan(_: Set<UITouch>, with: UIEvent?) {
     username.resignFirstResponder()
     password.resignFirstResponder()
     self.view.endEditing(true)
  }
}
 8
Author: hardik bar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-28 14:00:49

Jeśli używasz widoku przewijania, może to być znacznie prostsze.

Po prostu wybierz Dismiss interactively w storyboard.

 5
Author: JIE WANG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-09 15:52:24
  import UIKit

  class ItemViewController: UIViewController, UITextFieldDelegate {

  @IBOutlet weak var nameTextField: UITextField!

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

    // Called when 'return' key pressed. return NO to ignore.

    func textFieldShouldReturn(textField: UITextField) -> Bool {

            textField.resignFirstResponder()
             return true
     }

 // Called when the user click on the view (outside the UITextField).

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)    {
      self.view.endEditing(true)
  }
}
 4
Author: Prashant chaudhary,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-17 12:33:49

Ten jeden liner rezygnuje z klawiatury ze wszystkich(dowolnych) UITextField w UIView

self.view.endEditing(true)
 4
Author: Satnam Sync,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-24 10:01:13

Znalazłem najlepsze rozwiązanie, w tym zaakceptowaną odpowiedź od @ Esqarrouth, z pewnymi poprawkami:

extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboardView")
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

    func dismissKeyboardView() {
        view.endEditing(true)
    }
}

Linia tap.cancelsTouchesInView = false była krytyczna: zapewnia, że UITapGestureRecognizer nie uniemożliwia innym elementom widoku odbierania interakcji z użytkownikiem.

Metoda dismissKeyboard() została zmieniona na nieco mniej elegancką dismissKeyboardView(). Dzieje się tak dlatego, że w dość starej bazie kodowej mojego projektu, było wiele razy, gdzie dismissKeyboard() był już używany( domyślam się, że nie jest to rzadkość), powodując problemy z kompilatorem.

Wtedy, jak wyżej, takie zachowanie można włączyć w poszczególnych kontrolerach widoku:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround() 
}
 4
Author: Luke Harries,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-16 05:02:06

Jako początkujący programista może być mylące, gdy ludzie wytwarzają bardziej wykwalifikowane i niepotrzebne odpowiedzi...Nie musisz robić żadnych skomplikowanych rzeczy pokazanych powyżej!...

Oto najprostszy option...In obudowa klawiatury pojawia się w odpowiedzi na pole tekstowe - wewnątrz funkcji ekranu dotykowego wystarczy dodać funkcję resignFirstResponder. Jak pokazano poniżej - klawiatura zostanie zamknięta, ponieważ osoba udzielająca pierwszej pomocy zostanie zwolniona(wychodząc z łańcucha odpowiedzi)...

override func touchesBegan(_: Set<UITouch>, with: UIEvent?){
    MyTextField.resignFirstResponder()
}
 4
Author: RedSky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-09 15:33:04

Dla Swift3

Zarejestruj rozpoznawacz zdarzeń w viewDidLoad

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

Następnie musimy dodać gest do widoku w tym samym viewDidLoad.

self.view.addGestureRecognizer(tap)

Następnie musimy zainicjować zarejestrowaną metodę

func hideKeyBoard(sender: UITapGestureRecognizer? = nil){
    view.endEditing(true)
}
 3
Author: Sandu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-22 13:01:04

Aby zbudować z poprawną odpowiedź zawsze używam następującego rozszerzenia:

extension UIApplication {
    /// Dismiss keyboard from key window.
    open static func endEditing(_ force: Bool = false) {
        shared.keyWindow?.endEditing(force)
    }
}

W ten sposób, jeśli klasa, w której próbuję anulować edycję nie ma właściwości view lub nie jest podklasą UIView, mogę po prostu wywołać UIApplication.endEditing().

 3
Author: NoodleOfDeath,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:47

Możesz również dodać rozpoznawanie gestów stukania, aby zrezygnować z klawiatury. : D

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

    let recognizer = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
    backgroundView.addGestureRecognizer(recognizer)
}
    func handleTap(recognizer: UITapGestureRecognizer) {
    textField.resignFirstResponder()
    textFieldtwo.resignFirstResponder()
    textFieldthree.resignFirstResponder()

    println("tappped")
}
 2
Author: Satnam Sync,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-25 19:59:50

Inną możliwością jest po prostu dodanie dużego przycisku bez treści, który znajduje się pod wszystkimi widokami, które możesz potrzebować dotknąć. Nadaj jej nazwę działania:

@IBAction func dismissKeyboardButton(sender: AnyObject) {
    view.endEditing(true)
}

Problem z rozpoznawaniem gestów był dla mnie, że złapał również wszystkie dotyki, które chciałem otrzymać przez tableViewCells.

 2
Author: Timm Kent,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-24 21:49:33

Jeśli masz inne widoki, które również powinny otrzymać dotyk, musisz ustawić cancelsTouchesInView = false

TAK:

let elsewhereTap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
    elsewhereTap.cancelsTouchesInView = false
    self.view.addGestureRecognizer(elsewhereTap)
 2
Author: ph1lb4,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-19 16:02:07
override func viewDidLoad() {
        super.viewDidLoad()

self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap)))

}

func tap(sender: UITapGestureRecognizer){
        print("tapped")
        view.endEditing(true)
}

Spróbuj tego, to działa

 2
Author: Ramprasath Selvam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-27 07:34:01

W Swift 4 Dodaj @objc:

W viewDidLoad:

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
view.addGestureRecognizer(tap)

Funkcja:

@objc func dismissKeyboard() {
  view.endEditing(true)
}
 2
Author: user3856297,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-26 19:22:06

Dodaj to rozszerzenie do kontrolera ViewController:

 extension UIViewController {

// Ends editing view when touches to view 

open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)

    self.view.endEditing(true)
}
}
 2
Author: Jarvis The Avenger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-26 11:19:01

Gdy w widoku jest więcej niż jedno pole tekstowe

Aby postępować zgodnie z @ modocache ' s recommendation aby uniknąć wywołania view.endEditing(), możesz śledzić pole tekstowe, które stało się pierwszą odpowiedzią, ale jest to niechlujne i podatne na błędy.

Alternatywą jest wywołanie resignFirstResponder() na wszystkich polach tekstowych w kontrolerze viewcontroller . Oto przykład tworzenia zbioru wszystkich pól tekstowych (które w moim przypadku i tak były potrzebne do kodu weryfikacyjnego):

@IBOutlet weak var firstName: UITextField!
@IBOutlet weak var lastName: UITextField!
@IBOutlet weak var email: UITextField!

var allTextFields: Array<UITextField>!  // Forced unwrapping so it must be initialized in viewDidLoad
override func viewDidLoad()
{
    super.viewDidLoad()
    self.allTextFields = [self.firstName, self.lastName, self.email]
}

Z w przeciwieństwie do innych gier, nie jest to gra logiczna.]}

private func dismissKeyboard()
{
    for textField in allTextFields
    {
        textField.resignFirstResponder()
    }
}

Więc teraz możesz zadzwonić dismissKeyboard() w rozpoznawaniu gestów (lub gdziekolwiek jest to odpowiednie dla Ciebie). Wadą jest to, że musisz utrzymywać listę UITextFields podczas dodawania lub usuwania pól.

Komentarze mile widziane. Jeśli pojawi się problem z wywołaniem resignFirstResponder() na kontrolkach, które nie są pierwszą odpowiedzią, lub jeśli istnieje łatwy i gwarantowany sposób, aby śledzić bieżącą odpowiedź, chciałbym usłyszeć o to!

 1
Author: stone,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:34:54

Ćwiczyłem na uisearchbar . Zobacz też

import UIKit

class BidderPage: UIViewController,UISearchBarDelegate,UITableViewDataSource {

     let recognizer = UITapGestureRecognizer()

// Set recogniser as public in case of tableview and didselectindexpath.


    func searchBarTextDidBeginEditing(searchBar: UISearchBar)

    {

        recognizer.addTarget(self, action: "handleTap:")
        view.addGestureRecognizer(recognizer)

    }

    func handleTap(recognizer: UITapGestureRecognizer) {
        biddersearchbar .resignFirstResponder()
    }
    func searchBarTextDidEndEditing(searchBar: UISearchBar)
    {
        view .removeGestureRecognizer(recognizer)

    }
 1
Author: A.G,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-17 17:49:29

Wolę ten jednoliniowy :

view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "dismissKeyboardFromView:"))

Po prostu umieść to w funkcji override viewDidLoad w podklasowanym UIViewController, a następnie umieść następujący kod w nowym pustym pliku w projekcie o nazwie " UIViewController+dismissskeyboard.swift": {]}

import UIKit

extension UIViewController {
    // This function is called when the tap is recognized
    func dismissKeyboardFromView(sender: UITapGestureRecognizer?) {
        let view = sender?.view
        view?.endEditing(true)
    }
}
 1
Author: gammachill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-22 18:18:18

I got you fam

override func viewDidLoad() {
    super.viewDidLoad() /*This ensures that our view loaded*/
    self.textField.delegate = self /*we select our text field that we want*/   
    self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("dismissKeyboard")))
}

func dismissKeyboard(){ /*this is a void function*/
    textField.resignFirstResponder() /*This will dismiss our keyboard on tap*/
}
 1
Author: ChannelJuanNews,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-22 18:21:37

Znalazłem takie proste rozwiązanie: 1. Dodaj UITapGestureRecognizer do kontrolera widoku 2. Dodaj IBAction do UITapGestureRecognizer 3. W końcu możesz zrezygnować z pierwszej odpowiedzi

class ViewController: UIViewController
{

@IBOutlet var tap: UITapGestureRecognizer!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var textField: UITextField!
override func viewDidLoad()
{
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}


@IBAction func dismissUsingGesture(_ sender: UITapGestureRecognizer)
{
   self.textField.resignFirstResponder()
    label.text = textField.text!
}
}
 1
Author: Atka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-03 23:50:42

Oto zwięzły sposób na zrobienie tego:

let endEditingTapGesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:)))
endEditingTapGesture.cancelsTouchesInView = false
view.addGestureRecognizer(endEditingTapGesture)
 1
Author: Sam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-15 01:18:20