Swift version: 5.6
Although we can use pressesBegan()
and pressesEnded()
to read keypresses, they won’t show the on-screen keyboard and so won’t let you provide custom text input for users without a hardware keyboard. If you need that keyboard to be shown, you should create a class that adopts the UIKeyInput
protocol instead, which has just three requirements:
The only other thing you need to know is that your custom input control will show the keyboard when it becomes first responder. So, you should override the canBecomeFirstResponder
property of your subclass, setting it to true rather than the default of false.
To demonstrate this, we could create a simple UIView
subclass that draws text to the screen as it’s typed, like this:
class TextRenderingView: UIView, UIKeyInput {
// the string we'll be drawing
var input = ""
override var canBecomeFirstResponder: Bool {
true
}
var hasText: Bool {
input.isEmpty == false
}
func insertText(_ text: String) {
input += text
setNeedsDisplay()
}
func deleteBackward() {
_ = input.popLast()
setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
let attrs: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 32)]
let attributedString = NSAttributedString(string: input, attributes: attrs)
attributedString.draw(in: rect)
}
}
If you want to handle more complex user input, such as selecting ranges of text or drawing the caret, you should use the more advanced UITextInput
protocol instead.
SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 3.2
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.