Switch UIView and Keboard default Swift 4.2


I want to create a simple view switch keyboard, when users tap "Switch" button in corner to create a sticker page.


I will probably have to do this:

1. Call resignFirstResponder on the UITextField
2. After the animation finishes, set your inputView to nil
3. Call becomeFirstResponder on the text field




Full code :


import UIKit

class KeyboardStickerViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var texfil: UITextField!
    
    let textView = UITextView()
    let button = UIButton()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.button.addTarget(self, action: #selector(self.buttonAction), for: .touchUpInside)
        self.texfil.backgroundColor = .lightGray
        self.button.backgroundColor = .red
        self.view.addSubview(self.texfil)
        self.view.addSubview(self.button)
        self.texfil.delegate = self
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(_dismiss))
        view.isUserInteractionEnabled = true
        view.addGestureRecognizer(tap)
    }
    
    @objc func _dismiss() {
        self.texfil.resignFirstResponder()
    }
    
    @objc func buttonAction() {
        let keyboardView = UIView()
        self.texfil.becomeFirstResponder()
        
        if self.texfil.inputView == nil {
            self.texfil.inputView = keyboardView
            self.texfil.inputView?.autoresizingMask = .flexibleHeight
            self.texfil.reloadInputViews()
        }
    }
    
    @IBAction func touchDown(_ sender: UITextField) {
        self.texfil.inputView = nil
        self.texfil.reloadInputViews()
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        self.texfil.frame = CGRect(x: 0, y: 50, width: self.view.frame.size.width - 50, height: 50)
        self.button.frame = CGRect(x: self.view.frame.size.width - 100, y: 50, width: 99, height: 50)
        self.button.setTitle("Swicth", for: .normal)
        
    }
}

No comments: