如何在 SwiftUI 中设置按钮焦点? [英] How to set button focus in SwiftUI?

查看:30
本文介绍了如何在 SwiftUI 中设置按钮焦点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

!!!TVOS !!!

我有按钮列表,它以某种方式自动聚焦该列表中的第一个按钮(加载视图时).有什么方法可以使用 SwiftUI 聚焦该列表中的另一个按钮?

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?

我知道 UIKit 中有 preferredFocusedView 但我喜欢在 SwiftUI 中这样做.

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

感谢您的建议!

推荐答案

SwiftUI 2.0

注意:!!部分解决方案!!

以下方法,经 Xcode 12b5/tvOS 14 测试仅适用于堆栈,不适用于 List/ScrollView(在任何测试组合中).

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)
            }
        }
    }
}

这篇关于如何在 SwiftUI 中设置按钮焦点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆