iOS 和 TVOS 之间的 SwiftUI 共享按钮,focusable(_:onFocusChange:)' 在 iOS 中不可用

SwiftUI Share Button between iOS and TVOS, focusable(_:onFocusChange:)' is unavailable in iOS

我正在尝试在 iOS 和电视平台上共享(自定义)SwiftUI 按钮。我已经注意到每个平台的按钮看起来非常不同,但我的主要问题是“.focussable”。为了让按钮在 tvOS 中正确显示,我需要将可聚焦参数添加到按钮上。但是,在为 iOS 平台构建按钮时,出现以下错误:

focusable(_:onFocusChange:)' is unavailable in iOS

代码:

Button(action: {}) {
        HStack {
            if let image = icon, let uiimage = UIImage(named: image) {
                Image(uiImage: uiimage)
            }
            if let title = label {
                Text(title)
            }
        }
    }
    .focusable(true) { focused in
        withAnimation {
            self.background(Color.purple)
        }
    }

如何在此按钮上使用 focusable 并仍然保持它在 iOS 和 tvOS 之间共享?

对于这种情况你需要使用条件编译。为了更好的可重用性,可以将其包装在视图修饰符中,例如

struct DemoFocusableModifier: ViewModifier {
    private let isFocusable: Bool
    private let onFocusChange: (Bool) -> Void

    init (_ isFocusable: Bool = true, onFocusChange: @escaping (Bool) -> Void = { _ in }) {
        self.isFocusable = isFocusable
        self.onFocusChange = onFocusChange
    }

    @ViewBuilder
    func body(content: Content) -> some View {
#if os(tvOS)
        content
            .focusable(isFocusable, onFocusChange: onFocusChange)
#else
        content
#endif
    }
}

并使用(而不是你的.focusable)作为

  }
  .modifier(DemoFocusableModifier { focused in
        // content here
  })

准备了 Xcode 13 / iOS 15