Created
November 15, 2021 03:28
-
-
Save yosshi4486/6b3d10973546d73b963e6804ad136e17 to your computer and use it in GitHub Desktop.
Creating an own view subclass that can receive keyboard input.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CustomInputView: UIView, UIKeyInput { | |
private let label = UILabel() | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
label.tintColor = .label | |
label.font = .preferredFont(forTextStyle: .body, compatibleWith: nil) | |
label.text = "" | |
addSubview(label) | |
label.translatesAutoresizingMaskIntoConstraints = false | |
NSLayoutConstraint.activate([ | |
label.topAnchor.constraint(equalTo: topAnchor), | |
label.bottomAnchor.constraint(equalTo: bottomAnchor), | |
label.leadingAnchor.constraint(equalTo: leadingAnchor), | |
label.trailingAnchor.constraint(equalTo: trailingAnchor) | |
]) | |
} | |
required init?(coder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
// This is required. UIView returns false in `canBecomeFirstResponder` by default, but we have to meke this view become first responder. | |
override var canBecomeFirstResponder: Bool { | |
return true | |
} | |
var hasText: Bool { | |
return (label.text?.count ?? 0) > 0 | |
} | |
func insertText(_ text: String) { | |
label.text = label.text?.appending(text) | |
} | |
func deleteBackward() { | |
label.text = String(label.text!.dropLast()) | |
} | |
} | |
class ViewController: UIViewController { | |
let customView: CustomInputView = .init() | |
override func loadView() { | |
let view = UIView() | |
view.backgroundColor = .white | |
view.isUserInteractionEnabled = true | |
view.addSubview(customView) | |
customView.translatesAutoresizingMaskIntoConstraints = false | |
NSLayoutConstraint.activate([ | |
customView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), | |
customView.bottomAnchor.constraint(equalTo: view.bottomAnchor), | |
customView.leadingAnchor.constraint(equalTo: view.leadingAnchor), | |
customView.trailingAnchor.constraint(equalTo: view.trailingAnchor) | |
]) | |
self.view = view | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
} | |
override func viewDidAppear(_ animated: Bool) { | |
super.viewDidAppear(animated) | |
customView.becomeFirstResponder() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment