Skip to content

Instantly share code, notes, and snippets.

@PavelGnatyuk
Created March 29, 2020 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PavelGnatyuk/f095f38a8eaca8134d92ed3261442db2 to your computer and use it in GitHub Desktop.
Save PavelGnatyuk/f095f38a8eaca8134d92ed3261442db2 to your computer and use it in GitHub Desktop.
import UIKit
class ViewController: UIViewController {
private lazy var textFieldName: UITextField = {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.font = UIFont.preferredFont(forTextStyle: .body)
textField.borderStyle = .roundedRect
textField.delegate = self
return textField
}()
private lazy var textFieldLayout: [NSLayoutConstraint] = {
[textFieldName.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
textFieldName.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
textFieldName.centerYAnchor.constraint(equalTo: view.centerYAnchor)]
}()
private lazy var buttonDone: UIBarButtonItem = {
let button = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(tapOnDone(_:)))
button.isEnabled = false
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
navigationItem.rightBarButtonItem = buttonDone
view.addSubview(textFieldName)
NSLayoutConstraint.activate(textFieldLayout)
textFieldName.becomeFirstResponder()
}
}
extension ViewController: UITextFieldDelegate {
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
buttonDone.isEnabled = (!string.isEmpty || range.length < (textField.text ?? "").count)
return true
}
}
extension ViewController {
@objc func tapOnDone(_ sender: AnyObject?) {
debugPrint("File: \(#file) \(#function)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment