How to set button focus in SwiftUI?

五迷三道 提交于 2021-01-27 08:16:27

问题


!!! TVOS !!!

I have list of buttons and it somehow autofocus first button in that list (when view is loaded). Is there any way how to focus another button in that list using SwiftUI?

I know there is preferredFocusedView in UIKit but id like to do this in SwiftUI.

Thanks for any advice!


回答1:


SwiftUI 2.0

Note: !! Partial solution !!

The following approach, as tested with Xcode 12b5 / tvOS 14 works only with stacks and does not work (in any tested combination) for List/ScrollView.

Anyway for small on-screen sets of buttons it is applicable so worth posting.

struct DemoPreferredFocusView: View {
    @Namespace var ns
    @Environment(\.resetFocus) var resetFocus
    @AppStorage("initialButton") var initialButton: Int = 3

    var body: some View {
        VStack {
            ForEach(0..<10, id: \.self) { i in
                Button(action: {
                    print(">> tapped \(i)")
                    self.initialButton = i
                }) {
                    Text("Button \(i)")
                }
                .prefersDefaultFocus(i == initialButton, in: ns)
            }.focusScope(ns)
        }
        .onAppear {
            DispatchQueue.main.async {
                self.resetFocus.callAsFunction(in: ns)
            }
        }
    }
}


来源:https://stackoverflow.com/questions/60115506/how-to-set-button-focus-in-swiftui

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!