让列占据网格中所有可用空间的正确方法是什么?

问题描述 投票:0回答:1

这应该是我错过的一件简单的事情,所以我提前道歉。我有可重复使用的视图“TextRowView”,它有 2 个网格列,其中一个是固定宽度,另一个我想占用所有可用空间。

我不明白为什么它在 TruckView 预览中显示正确,但在列表视图中显示不正确

struct TextRowView: View {
    
    let columns = [
        GridItem(.fixed(140), alignment: .leading),
        GridItem(.flexible(), alignment: .leading)
    ]
    
    let title: String
    let value: String
    
    var body: some View {
        LazyVGrid(columns: columns) {
            Text(title)
                .bold()
            
            Text(value)
        }
    }
}

这是列表视图的单元格

import SwiftUI

struct TruckView: View {
    
    let truck: Truck
    
    var body: some View {
        VStack {
            TextRowView(title: "Year:", value: truck.year)
            
            TextRowView(title: "Make:", value: truck.make)
            
            TextRowView(title: "Model:", value: truck.model)
            
            TextRowView(title: "Driver:", value: truck.driver)
            
            TextRowView(title: "Truck #:", value: truck.truckNumber.formatted(.number.grouping(.never)))
        }
        .foregroundStyle(Color(hex: truck.foregroundColor))
        .padding()
        .background(RoundedRectangle(cornerRadius: 10)
            .fill(Color(hex: truck.backgroundColor)))
    }
}

这是列表视图

import SwiftUI

struct TripListView: View {
    
    @Environment(AppController.self) private var appController
    
    var body: some View {
        Group {
            List {
                ForEach(appController.filteredTrucks) { truck in
                    NavigationLink {
                        
                    } label: {
                        TruckView(truck: truck)
                    }
                }
            }
        }
    }
}

这是模拟器中的样子。

TruckListView Screenshot

这是预览中的 TruckView。

TruckView

这似乎有效,但我不确定这是否是处理这种情况的正确/最佳方法。

struct TextRowView: View {
    
    let columns = [
        GridItem(.fixed(140), alignment: .leading),
        GridItem(.flexible(minimum: UIScreen.main.bounds.width - 210), alignment: .leading)
    ]
    
    let title: String
    let value: String
    
    var body: some View {
        LazyVGrid(columns: columns) {
            Text(title)
                .bold()
            
            Text(value)
        }
    }
}
swiftui grid swiftui-list
1个回答
0
投票

尝试在

maxWidth: .infinity
上设置
LazyVGrid

// TextRowView

LazyVGrid(columns: columns) {
    // ...
}
.frame(maxWidth: .infinity) // 👈 HERE
© www.soinside.com 2019 - 2024. All rights reserved.