Skip to content

Instantly share code, notes, and snippets.

@elefantel
Last active May 2, 2017 23:09
Show Gist options
  • Save elefantel/79ef2629860325deee924275e8d73b13 to your computer and use it in GitHub Desktop.
Save elefantel/79ef2629860325deee924275e8d73b13 to your computer and use it in GitHub Desktop.
A view controller with scrolling that uses keyboard observing to shift input fields to remain above keyboard.
class RegistrationViewController: UIViewController, KeyboardDisplayChangeProtocol, UITableViewDelegate, UITableViewDataSource {
public enum FormField: String {
case name = "Name"
case surname = "Surname"
case age = "Age"
case email = "Email"
case telephone = "Telephone"
case username = "Username"
case password = "Password"
}
@IBOutlet weak var tableView: KBTableView!
var formFields: [FormField] = []
override func viewDidLoad() {
super.viewDidLoad()
addFormFields()
tableView.estimatedRowHeight = 60
tableView.rowHeight = UITableViewAutomaticDimension
tableView.tableFooterView = UIView(frame: .zero)
}
func addFormFields() {
formFields.append(.name)
formFields.append(.surname)
formFields.append(.age)
formFields.append(.email)
formFields.append(.telephone)
formFields.append(.username)
formFields.append(.password)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
addKeyboardObserver(on: view)
}
override func viewWillDisappear(_ animated: Bool) {
removeKeyboardObserver()
super.viewWillDisappear(animated)
}
func removeKeyboardObserver() {
tableView.removeKeyboardObserver()
}
func addKeyboardObserver(on view: UIView) {
tableView.addKeyboardObserver(on: view)
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return formFields.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: CustomCell.identifier) as? CustomCell
let formField = formFields[indexPath.row]
cell?.configure(title: formField.rawValue)
return cell!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment