【问题标题】:Different .listStyle() on iOS and WatchOS in a reusable component?iOS 和 WatchOS 上的不同 .listStyle() 在可重用组件中?
【发布时间】:2021-04-13 01:17:03
【问题描述】:

我很想在 iOS 和 WatchOS 之间重用列表布局,但 InsetGroupedListStyle() 在 WatchOS 上不可用。

在 iOS 上创建一个有条件地返回 InsetGroupedListStyle() 的助手是一个好方法,例如。 PlainListStyle() 在 WatchOS 上?

我试过了,但得到一个错误,我无法返回 ListStyle(这可能是由于 SwiftUI 需要在编译时知道特定类型)。

查看.swift

List {
    // ...
}
.listStyle(MyInsetGroupedListStyle())

Helpers.swift

public func MyInsetGroupedListStyle() -> ListStyle {
    #if os(watchOS)
        return PlainListStyle()
    #else
        return InsetGroupedListStyle()
    #endif
}

另一种方法是指定 listStyle 内联,但 swift 不支持表达式中的条件编译:

查看.swift

List {
    // ...
}
.listStyle(#if os(watchOS) PlainListStyle() #else InsetGroupedListStyle() #endif)

【问题讨论】:

标签: swiftui swiftui-list


【解决方案1】:

您可以使用 View 上的扩展来实现您想要的。这允许您添加 listStyle 修饰符以及您想要的操作系统所需的参数。

extension View {
    public func customListStyle() -> some View {
        #if os(watchOS)
        return self.listStyle(PlainListStyle())
        #else
        return self.listStyle(InsetGroupedListStyle())
        #endif
    }
}

然后你会像这样使用它:

List {
    // items in list go here
}
.customListStyle()

【讨论】:

  • 感谢您对这个模式的帮助!
【解决方案2】:

使用

  1. 不透明类型
public var myInsetGroupedListStyle: some ListStyle {
  #if os(watchOS)
  PlainListStyle()
  #else
  InsetGroupedListStyle()
  #endif
}
  1. 关闭
listStyle( {
  #if os(watchOS)
  PlainListStyle()
  #else
  InsetGroupedListStyle()
  #endif
} () )

【讨论】:

  • 谢谢!太糟糕了,我只能选择一个答案,因为您和 Andrews 的答案都很棒而且很有用。
猜你喜欢
  • 1970-01-01
  • 2022-01-07
  • 2016-05-28
  • 1970-01-01
  • 1970-01-01
  • 2020-04-11
  • 2017-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多