KeyboardStrut is an utility to prevent the iOS virtual keyboard to cover your text fields and obscure typing. This library provides a view - KeyboardStrutView - that adapts its size to the keyboard size. It can be used as a dynamic strut to control the overall layout by placing the other views relative to the KeyboardStrutView.
Let's say there's a form with a text field that is shown at the bottom of the screen like this:
let nameLabel = UILabel(frame: .zero)
nameLabel.text = "Enter your name:"
let nameField = UITextField(frame: .zero)
nameField.placeholder = "type your name here"
let form = UIStackView(arrangedSubviews: [
nameLabel,
nameField,
KeyboardStrutView(frame: .zero),
])
form.axis = .vertical
form.alignment = .center
self.view.addSubview(form)
form.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
form.leftAnchor.constraint(equalTo: self.view.leftAnchor),
form.rightAnchor.constraint(equalTo: self.view.rightAnchor),
form.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -200),
])
Without KeyboardStrutView when the virtual keyboard is open, it goes on top of the text field, and the form becomes hidden. The KeyboardStrutView fixes this issue: it pushes the form up or down as needed.
KeyboardStrutView can also be placed outside of the form at the bottom of your view if you set up the constraints for it:
let keyboardStrut = KeyboardStrutView(frame: .zero)
keyboardStrut.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(keyboardStrut)
NSLayoutConstraint.activate([
keyboardStrut.leftAnchor.constraint(equalTo: self.view.leftAnchor),
keyboardStrut.rightAnchor.constraint(equalTo: self.view.rightAnchor),
keyboardStrut.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
])
self.view.addSubview(form)
form.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
form.leftAnchor.constraint(equalTo: self.view.leftAnchor),
form.rightAnchor.constraint(equalTo: self.view.rightAnchor),
form.bottomAnchor.constraint(equalTo: keyboardStrut.topAnchor, constant: -200),
])
This can also be used in a XIB or Storyboard:
link |
Stars: 0 |
Last commit: 2 weeks ago |
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics