onFocusChange 未在 SwiftUI tvOS 中触发 [英] onFocusChange not triggered in SwiftUI tvOS

查看:10
本文介绍了onFocusChange 未在 SwiftUI tvOS 中触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置 onFocusChange 并在视图上单击操作功能.但是 onFocusChange 永远不会被调用.

I am trying to set onFocusChange and click action function on a view. But onFocusChange is never called.

ScrollView(.horizontal, showsIndicators: false) {
    HStack(alignment: .center, spacing: 5) {
        ForEach(self.videos, id: .id) { video in
            
            Button(action: {
                print("clicked")
            }){
                ItemView(vid: video)
                    .cornerRadius(5).padding(1)
            }.focusable(true, onFocusChange: {
                hasFocus in
                print("focused")
            })
        }
    }
}

如果我在 ItemView() 内移动按钮视图,onFocusChange 有效,但点击操作无效.

If I move the button view inside the ItemView(), the onFocusChange works but the click action doesn't.

推荐答案

问题的目标不明确,但这里有一个简单的替代方法演示,用于管理重点 &按钮单击使用自定义按钮样式.也许这会有所帮助.

The goal the question is unclear, but here is a simple demo of alternate approach to have managed focused & button click using custom button style. Maybe this will be helpful.

使用 Xcode 12/tvOS 14(模拟器)测试 - 比较常规按钮与自定义按钮

Tested with Xcode 12 / tvOS 14 (Simulator) - compare regular button vs custom button

struct MyButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .scaleEffect(configuration.isPressed ? 1.2 : 1)
    }
}

struct ContentView: View {
    @State private var focused = false
    var body: some View {
        VStack {
            Button(action: {
                print(">>>> custom button")
            }) { LabelView() }.buttonStyle(MyButtonStyle())

            Button("Regular Button") {
                print(">> regular button")
            }
        }
    }
}

struct LabelView: View {
    @Environment(.isFocused) var focused: Bool
    var body: some View {
        RoundedRectangle(cornerRadius: 25.0)
            .frame(width: 200, height: 100)
            .foregroundColor(focused ? .blue : .gray)
            .overlay(Text("Title").foregroundColor(.white))
    }
}

这篇关于onFocusChange 未在 SwiftUI tvOS 中触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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