SwiftUI如何在横向和纵向中重新排序

时间:2019-12-16 01:43:19

标签: swiftui

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

我们该怎么做?

ModularGridStyle(columns: 2, rows: 3)
如果设备处于横向状态,则

列和行需要不同。

这是视图

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

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

3 个答案:

答案 0 :(得分: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
            )
        )
    }
}

答案 1 :(得分:0)

这是可行的方法:

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)
    }
}

答案 2 :(得分:0)

我个人更喜欢使用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)
            )
        }
    }
}