【问题标题】:How do I use TextInput for WatchOS in swiftUI如何在 swiftUI 中为 WatchOS 使用 TextInput
【发布时间】:2019-11-16 02:23:18
【问题描述】:

通常我会使用presentTextInputControllerWithSuggestions() 来显示TextInput 字段。但这在 swiftUI 中不可用,因为它是 WKInterfaceController 的一个函数。我必须为此使用 WKInterfaceController 吗? 我在文档中找不到任何内容。

【问题讨论】:

    标签: watchkit apple-watch swiftui


    【解决方案1】:

    这将通过 SwiftUI 中的 TextField 来完成。

    【讨论】:

    • 如此简单,就像一个魅力。非常感谢!
    • 虽然我在 WatchOS 中成功使用了 TextField,但我找不到如何向输入添加建议。有什么指点吗?
    【解决方案2】:

    您可以在 SwiftUI 中使用 View 扩展:

    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: View {
    
        var body: some View {
            Button(action: {
                presentInputController()
            }, label: {
                Text("Press this button")
            })
        }
        
        private func presentInputController() {
            presentInputController(withSuggestions: []) { result in
                // handle result from input controller
            }
        }
    }
    

    【讨论】:

    • 谢谢!快速提问:我应该只能从我的 ContentView 调用它吗?我在struct ContentView: View 块下添加了这个扩展,我试图从Button(action: { presentInputControler(..) }) 调用它,但是当我点击预览中的按钮时,什么也没有发生。
    • @TobiasFünke 我已经添加了一个示例来回答如何使用这个扩展
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 2019-12-26
    • 2015-08-24
    • 2020-09-03
    相关资源
    最近更新 更多