I'm trying my hand at making a custom keyboard while learning Swift. In my keyboard, each key is a separate UIView with a UILabel in it. Each UILabel has a tag of 1. At first I coded each key's input manually, but I decided to optimize the code and set a function that takes the UILabel's text and sets it as input but for some reason the keyboard is crashing (no log
Note 1: One key is shown to simplify things
Note 2: The gesture is defined elsewhere, it'd not causing the crash
Here's my code:
override func viewDidLoad() {
super.viewDidLoad()
var Qkey = UIView(frame: CGRectMake(3, 11, 26, 38))
var Q = UILabel(frame: CGRectMake(5, 8, 17, 27))
Q.tag = 1
Q.text = "Q"
Qkey.addSubview(Q)
tapRec1.addTarget(self, action: "keyPressed:")
Qkey.addGestureRecognizer(tapRec1)
self.view.addSubview(Qkey)
}
func keyPressed(sender: UIView){
let theLabel : UILabel! = sender.viewWithTag(1) as UILabel;
var string = theLabel.text!
(textDocumentProxy as UIKeyInput).insertText("\(theLabel)")
}
Error observed in the log:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITapGestureRecognizer viewWithTag:]: unrecognized selector sent to instance 0x798bba30'
Essentially what I'm trying to do is for the UIView (sender) on which the function is called on, to grab all the subviews (UILabels) with tag 1, and set their text as the keyboard input. Even doing it on on key crashes:( Any help is greatly appreciated. Thanks!
Finally figured it out. Here's the working code:
func keyPressed(sender: UITapGestureRecognizer){
for subview in sender.view!.subviews as [UIView] {
if subview.tag == 1
{
let label = subview as UILabel
if capsLockOn {
(textDocumentProxy as UIKeyInput).insertText("\(label.text!.uppercaseString)")
} else {
(textDocumentProxy as UIKeyInput).insertText("\(label.text!.lowercaseString)")
}
}
}
}