The Finnternet Like the Internet but with more me

Get Swifty: Input Accessory View

Have you ever used an app that adds a button to the top of the keyboard when you are typing in a textfield? My first thought was to detect the keyboard & shift the button from the bottom to be at the right height but thankfully Apple provides a much easier solution; input accessory views.

Input Accessory View

Achieving the setup seen above is as simple as programatically creating a button in your view controller’s viewDidLoad method & attaching it to the IBOutlet for your textfield.

class ViewController: UIViewController {

    @IBOutlet weak var inputTextField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let inputButton = UIButton(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 60))
        inputButton.backgroundColor = #colorLiteral(red: 0.9372549057, green: 0.3490196168, blue: 0.1921568662, alpha: 1)
        inputButton.setTitle("Do something cool", for: .normal)
        inputButton.setTitleColor(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: .normal)
        inputButton.addTarget(self, action: #selector(ViewController.somethingCool), for: .touchUpInside)
        
        inputTextField.inputAccessoryView = inputButton
    }
    
    @objc func somethingCool() {
        print("Completed a sweet bunny hop on your scooter!")
    }
}