programing tip

UITextField 외부의 아무 곳이나 터치 할 때 키보드를 닫는 방법 (신속하게)?

itbloger 2020. 12. 6. 21:15
반응형

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

스크롤 뷰 외부를 탭하면 작동하지만 스크롤 뷰를 탭하면 아무 일도 일어나지 않고 키보드가 숨겨지지 않습니다.

도청 할 때 키보드를 기각 할 수있는 방법이 있나요 어디서나 텍스트 필드 밖에서는? 감사


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에서 호출


이것을 시도하면 테스트되고 작동합니다.

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

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

이 경우 선택 사항 중 하나로 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()
    }
}

ScrollView와 함께 작동하는 Swift 3 용 작업 솔루션

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

이 문제에 대해 언급하고 사용했던 또 다른 질문 입니다. 수락 된 답변은 더 이상 Swift 3에서 작동하지 않습니다. 현재 선택한 답변은 아래 답변이어야합니다.


이것 좀 봐.

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

세부

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

Swift 3의 경우

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

이것은 입력 항목의 개수에 관계없이 입력 영역 외부를 터치했을 때 작동합니다.

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

나는 같은 문제가 있었고 마침내 그것을 해결했습니다!

Storyboard에서 TapGestureRecognizer를 설정 한 다음 ViewController에서 콘센트를 설정합니다.

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

그리고 그것은 작동합니다

도움이 되길 바랍니다!


Every touch different of text field dismiss the keyboard or use resignfirstresponder

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

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
}

I created this method in Obj-C that hides a keyboard no matter where the user is currently typing:

//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];
    }
}

I hope that that is translate-able into Swift and makes sense. It can be called anywhere in the application and will hide the keyboard no matter what VC you're on or anything.


Go to Keyboard Type and Select Default or whatever you need the TextField for. Then override a method call it whatever you want i usually call it touchingBegins. Below is what you forgot to add

super.touchingBegins(touches, withEvent: event)
 }

Introduce a tap gesture recogniser and set and action for it.

Use the code:

nameofyourtextfield.resignfirstresponder()


//In swift 4..It worked for me.

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
    }

//Call this function setupKeyboardDismissRecognizer() in viewDidLoad


In Swift4

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

In Swift 4 or 5 You can use 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)
  }
}

참고URL : https://stackoverflow.com/questions/32281651/how-to-dismiss-keyboard-when-touching-anywhere-outside-uitextfield-in-swift

반응형