Skip to content

Instantly share code, notes, and snippets.

@dcramps
Last active July 30, 2019 15:40
Show Gist options
  • Select an option

  • Save dcramps/c0c1ae078c32a39a1238e3243f828817 to your computer and use it in GitHub Desktop.

Select an option

Save dcramps/c0c1ae078c32a39a1238e3243f828817 to your computer and use it in GitHub Desktop.
Keyboard stuff
import UIKit
class KeyboardThing: UIViewController {
let toolbar = UIView()
let input = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
setUpViews()
NotificationCenter.default.addObserver(
self,
selector: #selector(frameChange),
name: UIResponder.keyboardWillChangeFrameNotification,
object: nil)
}
private func setUpViews() {
let tap = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:)))
view.isUserInteractionEnabled = true
view.addGestureRecognizer(tap)
view.backgroundColor = .white
toolbar.layoutMargins = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)
toolbar.backgroundColor = .black
toolbar.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(toolbar)
input.translatesAutoresizingMaskIntoConstraints = false
input.backgroundColor = .white
toolbar.addSubview(input)
NSLayoutConstraint.activate([
toolbar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
toolbar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
toolbar.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
toolbar.heightAnchor.constraint(equalToConstant: 88),
input.topAnchor.constraint(equalTo: toolbar.layoutMarginsGuide.topAnchor),
input.leadingAnchor.constraint(equalTo: toolbar.layoutMarginsGuide.leadingAnchor),
input.bottomAnchor.constraint(equalTo: toolbar.layoutMarginsGuide.bottomAnchor),
input.trailingAnchor.constraint(equalTo: toolbar.layoutMarginsGuide.trailingAnchor),
])
}
@objc private func frameChange(n: NSNotification) {
guard let keyboardFrame = n.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
// this frame represents the part of the screen that is being covered by the keyboard.
let intersectionFrame = view.frame.intersection(keyboardFrame)
// a 0 height intersection means the keyboard isn't in the way anymore, so reset to identity
if intersectionFrame.height == 0 {
toolbar.transform = .identity
} else {
toolbar.transform = CGAffineTransform.identity.translatedBy(x: 0.0, y: -intersectionFrame.height + view.safeAreaInsets.bottom)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment