I made a calculator app (swift), and I set up some UIKeyCommands so that if the user has a bluetooth keyboard, they can type numbers/symbols into the calculator.
They work like so:
UIKeyCommand(input: "4", modifierFlags: [], action: "TypeFourInCalculator:")
func TypeFourInCalculator(sender: UIKeyCommand) {
btn4Press(UIButton)
}
That all worked well, adding a four into the calculator when the user pressed the four key (even though the calculator itself has no text field). However: I also have a couple of standard text fields, and I want the UIKeyCommands to stop when the user goes into one of those text fields (so they can type regularly with the BT keyboard again). Without disabling the UIKeyCommands, typing results in calculator functions and no input into the text field.
So I tried this in an attempt to disable UIKeyCommands when the text field becomes the first responder:
let globalKeyCommands = [UIKeyCommand(input: "4", modifierFlags: [], action: "TypeFourInCalculator:"), UIKeyCommand(input: "5", modifierFlags: [], action: "TypeFiveInCalculator:")]
override var keyCommands: [UIKeyCommand]? {
if powertextfield.isFirstResponder() == false { // if the user isn't typing into that text field
return globalKeyCommands // use key commands
} else { // if the user is typing
return nil // disable those UIKeyCommands
}
This works occasionally but yet often doesn't work. If the user has not typed anything with the BT keyboard yet (i.e. not activating the key commands, I guess) then they can type with the BT keyboard as normal into a text field. But if they have already been typing numbers into the calculator via UIKeyCommand, they can not type into the text field (well, sometimes it works with normal behavior, sometimes it fails like it did before I added that preventative code). Typed text just doesn't appear in that text field and, instead, it just calls the calculator command.
So what can I do to disable these UIKeyCommands when the user starts typing in a normal text field?
keyCommands
is being queried to make sure it's actually being updated when you think it is being updated. – Frontpage