RxSwift implements clicking anywhere on the page to close the keyboard

In iOS development, we often need to implement the keyboard closing operation. Generally, we click on the blank space of the page to close the keyboard. There are two commonly used methods:

Implemented in the proxy method:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        textFiled.resignFirstResponder() //方法一
        self.view.endEditing(true) //方法二
    }

However, this method often makes it difficult to click on a blank space on the page when there are many interface controls, making it difficult to hide the keyboard.

Then we thought that we can monitor the tap gesture of the view of the page, and put away the keyboard when the page is clicked. This method is implemented as follows:

//注册点击事件
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:))))

@objc func handleTap(sender:UITapGestureRecognizer) {
        if sender.state == .ended {
            textField.resignFirstResponder()
        }
        sender.cancelsTouchesInView =false
    }

The above is the general implementation method. Let’s use RxSwift+RxCocoa to implement this method :

//首先需要导入RxSwift和RxCocoa
import RxSwift
import RxCocoa

fileprivate let disposeBag = DisposeBag()
    
override func viewDidLoad() {
    super.viewDidLoad()

    //添加一个点击手势
    let tapBackground = UITapGestureRecognizer()
    view.addGestureRecognizer(tapBackground)
        
    tapBackground.rx.event.subscribe(onNext: { [weak self] _ in
        self?.view.endEditing(true)
    }).disposed(by: disposeBag) 

}

Specific RxSwift and RxCocoa can be installed using CocoaPods

platform :ios,’10.0’
use_frameworks!
target ‘项目名’ do
pod 'RxSwift',    '~> 4.0'
pod 'RxCocoa',    '~> 4.0'
pod 'IQKeyboardManagerSwift'
end

Of course, you can also use IQKeyboardManagerSwift, a third-party keyboard management tool, to handle the closing of the keyboard.

Guess you like

Origin blog.csdn.net/qq_37269542/article/details/89309465