SwiftUI跨iOS和tvOS共享Button时focusable接口iOS不可用如何解决
跨iOS/tvOS兼容focusable修饰符实现方案
核心原理
Swift提供编译时平台判断能力,仅在tvOS平台下编译focusable相关逻辑,iOS平台自动忽略该段代码即可解决编译报错问题。
方案1:直接改造现有代码
在focusable修饰符外层加平台编译判断即可:
Button(action: {}) { HStack { if let image = icon, let uiimage = UIImage(named: image) { Image(uiImage: uiimage) } if let title = label { Text(title) } } } #if os(tvOS) .focusable(true) { focused in withAnimation { self.background(Color.purple) } } #endif
方案2:封装为通用View扩展(推荐,适合多场景复用)
如果多个组件都需要用到同款focusable逻辑,可以封装为自定义修饰符,调用更简洁:
extension View { @ViewBuilder func tvOSFocusable(_ isFocusable: Bool = true, onFocusChange: @escaping (Bool) -> Void) -> some View { #if os(tvOS) self.focusable(isFocusable, onFocusChange: onFocusChange) #else self #endif } }
调用时代码无需加额外判断,自动适配双平台:
Button(action: {}) { // 按钮内容同之前实现 } .tvOSFocusable(true) { focused in withAnimation { self.background(Color.purple) } }
内容的提问来源于stack exchange,提问作者Steven B.
相关产品推荐
相关产品推荐

