【问题标题】:SwiftUI how to Reorder in Landscape and PortraitSwiftUI 如何在横向和纵向中重新排序
【发布时间】:2019-12-16 01:43:19
【问题描述】:

我们使用自定义 gridView 在网格中显示所有产品。 问题是……如果设备是横向或纵向,我们需要重新排序。

我们该怎么做?

ModularGridStyle(columns: 2, rows: 3)

如果设备是横向的,列和行需要不同。

这里是视图

var body: some View {
Grid(self.products) { product in
                    Text("\(product.name)")

                }
                .gridStyle(
                    ModularGridStyle(columns: 2, rows: 3)
                )
}

【问题讨论】:

标签: swiftui


【解决方案1】:

我会使用verticalSizeClass

@Environment(\.verticalSizeClass) private var verticalSizeClass: UserInterfaceSizeClass?

var body: some View {
    Grid(self.products) { Text(verbatim: "\($0.name)") }
        .gridStyle(
            ModularGridStyle(
                columns: self.verticalSizeClass == .compact ? 3 : 2, 
                rows: self.verticalSizeClass == .compact ? 2 : 3
            )
        )
    }
}

【讨论】:

    【解决方案2】:

    我个人更喜欢使用 GeometryReader 为纵向/横向设置不同的视图。当然,这有点多余,但通常你还有其他属性也会发生变化:

    var body: some View {
        GeometryReader() { g in
            if g.size.width < g.size.height {
                // view in portrait mode
                Grid(self.products) { product in
                    Text("\(product.name)")
                }
                .gridStyle(
                    ModularGridStyle(columns: 2, rows: 3)
                )
            } else {
                // view in landscape mode
                Grid(self.products) { product in
                    Text("\(product.name)")
                }
                .gridStyle(
                    ModularGridStyle(columns: 3, rows: 2)
                )
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      这是可能的方法:

      private var deviceOrientationPublisher = NotificationCenter.default.publisher(for:
          UIDevice.orientationDidChangeNotification)
      
      @State var dimention: (Int, Int) = (2, 3)
      var body: some View {
          Grid(self.products) { product in
              Text("\(product.name)")
      
          }
          .gridStyle(
              ModularGridStyle(columns: dimention.0, rows: dimention.1)
          )
          .onReceive(deviceOrientationPublisher) { _ in
              self.dimention = UIDevice.current.orientation.isLandscape ? (3, 2) : (2, 3)
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-29
        • 2015-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-22
        相关资源
        最近更新 更多