问题
!!! 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