Skip to content

Instantly share code, notes, and snippets.

@austinzheng
Last active January 20, 2022 15:14
Show Gist options
  • Save austinzheng/a8563c6babfd61401be3 to your computer and use it in GitHub Desktop.
Save austinzheng/a8563c6babfd61401be3 to your computer and use it in GitHub Desktop.
Simple UIKeyInput example
import UIKit
/// A very simple example view that can accept keyboard input and add or delete text from an enclosed label.
class CustomTextInputView : UIControl, UIKeyInput {
var label : UILabel?
override func canBecomeFirstResponder() -> Bool {
return true
}
init() {
super.init(frame: CGRectZero)
build()
addTarget(self, action: Selector("onTap:"), forControlEvents: .TouchUpInside)
}
@objc private func onTap(_: AnyObject) {
// When the view is tapped, it becomes the first responder. If the keyboard is not already on screen, it will appear.
becomeFirstResponder()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
build()
addTarget(self, action: Selector("onTap:"), forControlEvents: .TouchUpInside)
}
/// Programmatically create and configure the enclosed label.
private func build() {
let lbl = UILabel()
lbl.setTranslatesAutoresizingMaskIntoConstraints(false)
lbl.numberOfLines = 0
addSubview(lbl)
lbl.font = UIFont(name: "HelveticaNeue-Light", size: 14.0)!
// Constrain!
let views = ["lbl": lbl]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-[lbl]-|", options: nil, metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[lbl]-|", options: nil, metrics: nil, views: views))
label = lbl
}
// MARK: UIKeyInput
func hasText() -> Bool {
return label?.text?.isEmpty ?? false
}
func insertText(text: String) {
label?.text = (label?.text ?? "") + text
}
func deleteBackward() {
if let text = label?.text where !text.isEmpty {
let newText = text[text.startIndex..<text.endIndex.predecessor()]
label?.text = newText
}
}
}
@ruddfawcett
Copy link

Hey! I am working on something similar to this, but can't seem to get it to work with a very basic implementation — do you have any thoughts? (Gist: https://gist.github.com/ruddfawcett/bb993a1783fb0747d219cef6027c2486)

@cody1024d
Copy link

@ruddfawcett @austinzheng Either of you guys get this working? I seemingly am not getting the keyboard to appear when I add my custom UIKeyInput view to a view controller, and press on it (which should make it become the first responder)

@pooja816
Copy link

pooja816 commented Feb 5, 2018

How to change the keyboard to numberPad?

@NeilsUltimateLab
Copy link

NeilsUltimateLab commented Apr 18, 2020

How to change the keyboard to numberPad?
declare a variable in above CustomTextInputView class.
var keyboardType: UIKeyboardType = .numberPad

@snamrata007
Copy link

How to change textContentType to otp

@NeilsUltimateLab
Copy link

var textContentType: UITextContentType = .oneTimeCode

If you like, you can check this link OneTimeCodeField

@jagan510710
Copy link

jagan510710 commented Dec 1, 2020

Hi,

I am taking input from external device. if I use canBecomeFirstResponder true, keyboard coming on top of the View. is it possible to hide the keyboard?.

here is my code.

class KeyView: UIView, UIKeyInput {

    var badgeStr = ""
    override var canBecomeFirstResponder: Bool {
        true
    }
    var hasText: Bool {
        badgeStr.isEmpty == false
    }
    
    func insertText(_ text: String) {
            badgeStr += text
        if badgeStr.count == 1 {
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                if self.badgeStr.count > 3 {
                    self.enteredBadge!(self.badgeStr)
                }
                self.badgeStr = ""
                self.hasEnter = false
            }
        }
    }
    
    func deleteBackward() {
        _ = badgeStr.popLast()
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment