Skip to content

Instantly share code, notes, and snippets.

@nkmrh
Created May 17, 2018 09:23
Show Gist options
  • Save nkmrh/efcbb9117438918b8a3970b794f613b2 to your computer and use it in GitHub Desktop.
Save nkmrh/efcbb9117438918b8a3970b794f613b2 to your computer and use it in GitHub Desktop.
UITextfield がキーボードに隠れないようにする ref: https://qiita.com/nkmrh/items/8bd2be71dd8cc1f6e4c1
import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
private var scrollView: UIScrollView!
private var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
scrollView = UIScrollView()
scrollView.backgroundColor = .gray
scrollView.alwaysBounceVertical = true
scrollView.keyboardDismissMode = .interactive
view.addSubview(scrollView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
textField = UITextField()
textField.backgroundColor = .white
textField.delegate = self
scrollView.addSubview(textField)
textField.translatesAutoresizingMaskIntoConstraints = false
textField.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: view.bounds.height - 100).isActive = true
textField.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillShow),
name: .UIKeyboardWillShow,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillHide),
name: .UIKeyboardWillHide,
object: nil)
}
@objc private func keyboardWillShow(notification: Notification) {
guard let keyboardFrame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect else { return }
let offset = textField.frame.maxY - keyboardFrame.minY
if offset > 0 {
scrollView.contentOffset.y = offset
}
}
@objc private func keyboardWillHide(notification: Notification) {
scrollView.contentOffset.y = -scrollView.safeAreaInsets.top
}
}
extension ViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
let viewController = ViewController()
let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 768, height: 1024))
window.rootViewController = viewController
window.makeKeyAndVisible()
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = window
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment