Wednesday, September 7, 2016

Adjust UITableView for Keyboard in Swift

You've got a table full of cells. Now you add a text input of some kind. I used to avoid this whenever possible because it was so aggravating trying to show the last few cells above the keyboard. I used to do something similar every time, but it always changed a little and there were always annoying bugs that never seemed to die.

`TableViewInsetsAdjusting` to the rescue!

final class ExampleTableViewController: UITableViewController, TableViewInsetsAdjusting {
    
    private var inputBar: TextInputBar = TextInputBar.viewFromNib()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupInsetAdjust()
    }
    
    override func canBecomeFirstResponder() -> Bool {
        return true
    }
    
    override var inputAccessoryView: UIView? {
        return inputBar
    }
    
    deinit {
        takeDownInsetAdjust()
    }
    
}

Just conform to TableViewInsetsAdjusting, call `setupInsetAdjust` and you'll have your insets adjusting automatically for you whenever the keyboard comes up.

Don't forget to call `takeDownInsetAdjust` on your way out.

That's it!!! All your problems are now solved!

Here's the repo: TableViewInsetsAdjusting Repo

No comments:

Post a Comment