2

So I'm working on a tvos app in swift and I was wondering if it's possible to disable dictation support for a custom UITextField. It doesn't really work well for it and I don't want the user to be able to do so

2 Answers2

0

Did you try to use the textfield's keyboardType property? Maybe you can change the text input type, so the dictation function is automatically not shown.

Documentation: https://developer.apple.com/library/tvos/documentation/UIKit/Reference/UITextInputTraits_Protocol/index.html#//apple_ref/occ/intfp/UITextInputTraits/keyboardType

matthiaswitt
  • 196
  • 9
0

This is a Swift 4 solution based on @BadPirate's hack. It will trigger the initial bell sound stating that dictation started, but the dictation layout will never appear on the keyboard.

This will not hide the dictation button from your keyboard: for that the only option seems to be to use an email layout with UIKeyboardType.emailAddress.


In viewDidLoad of the view controller owning the UITextField for which you want to disable dictation:

// Track if the keyboard mode changed to discard dictation
NotificationCenter.default.addObserver(self,
                                       selector: #selector(keyboardModeChanged),
                                       name: UITextInputMode.currentInputModeDidChangeNotification,
                                       object: nil)

Then the custom callback:

@objc func keyboardModeChanged(notification: Notification) {
    // Could use `Selector("identifier")` instead for idSelector but
    // it would trigger a warning advising to use #selector instead
    let idSelector = #selector(getter: UILayoutGuide.identifier)

    // Check if the text input mode is dictation
    guard
        let textField = yourTextField as? UITextField
        let mode = textField.textInputMode,
        mode.responds(to: idSelector),
        let id = mode.perform(idSelector)?.takeUnretainedValue() as? String,
        id.contains("dictation") else {
            return
    }

    // If the keyboard is in dictation mode, hide
    // then show the keyboard without animations
    // to display the initial generic keyboard
    UIView.setAnimationsEnabled(false)
    textField.resignFirstResponder()
    textField.becomeFirstResponder()
    UIView.setAnimationsEnabled(true)

    // Do additional update here to inform your
    // user that dictation is disabled
}
agirault
  • 2,509
  • 20
  • 24