1

I'm building my first watchOS app, and I'm new to Swift but loving it so far.

I'm trying to create a button that, when pressed, starts listening in dictation mode. I've seen this done in other watchOS apps (e.g. Drafts).

Is this possible in SwiftUI alone (e.g. via some modifier of TextField), or do I need to bridge into UIKit?

If only the latter is possible, I've tried this approach but clicking the button doesn't seem to do anything. What am I missing?

import SwiftUI

struct ContentView: View {
    var body: some View {
        Button(action: {
            presentInputController(withSuggestions: ["testing"], completion: {(answer) -> Void in })
        }) {
            Image(systemName: "plus")
                .font(.largeTitle)
        }
    }
}

extension View {
    typealias StringCompletion = (String) -> Void
    
    func presentInputController(withSuggestions suggestions: [String], completion: @escaping StringCompletion) {
        WKExtension.shared()
            .visibleInterfaceController?
            .presentTextInputController(withSuggestions: suggestions,
                                        allowedInputMode: .plain) { result in
                
                guard let result = result as? [String], let firstElement = result.first else {
                    completion("")
                    return
                }
                
                completion(firstElement)
            }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
7
  • You should look up articles on interfacing with UIKit Commented Nov 22, 2021 at 11:48
  • Yes, and I have. Should I infer from your response that it’s not possible to do it in SwiftUI alone? Commented Nov 22, 2021 at 19:25
  • No, SwiftUI is for ui and in its early stages. Anything more than the basics it has to be in uikit. Your code is not correct you are interfacing incorrectly. Commented Nov 22, 2021 at 19:30
  • Thanks. Would you mind telling me how, or pointing me to an appropriate article, or giving me a tip for what to search? I keep finding articles about pulling in custom controllers and views, when I just need to call this UIKit function. Commented Nov 22, 2021 at 22:39
  • The Apple tutorial and this SO post Commented Nov 22, 2021 at 23:11

1 Answer 1

0

Instead of using TextField for calling text input view, since WatchOS 9 you can use TextFieldLink

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.