簡體   English   中英

如何從 Mac OS 中的 SwiftUI 列表中刪除底部/頂部項目填充

[英]How to remove bottom/top item padding from SwiftUI List in Mac OS

我很難使用 SwiftUI 從 MacOS 中的單元格中刪除所有填充。 即使在 Apple 的代碼中,我似乎也無法做到這一點!

https://developer.apple.com/tutorials/swiftui/creating-a-macos-app

例如,在 Xcode 中MacLandmarks文件夾的LandMarkList中,我在forEach的末尾放置了一個.listRowInsets(EdgeInsets()) ,這樣代碼如下所示:

struct LandmarkList: View {
    @EnvironmentObject private var userData: UserData
    @Binding var selectedLandmark: Landmark?
    @Binding var filter: FilterType

    var body: some View {
        List(selection: $selectedLandmark) {
            ForEach(userData.landmarks) { landmark in
                if (!self.userData.showFavoritesOnly || landmark.isFavorite)
                    && (self.filter == .all
                        || self.filter.category == landmark.category
                        || (self.filter.category == .featured && landmark.isFeatured)) {
                    LandmarkRow(landmark: landmark).tag(landmark)
                        .background(Color.red)
                }
            }
            .listRowInsets(EdgeInsets())
        }
    }
}

我還在每個單元格中添加了紅色背景色。 這是我得到的結果:

頂部和底部的空間

關鍵是我似乎無法擺脫這個列表的單元格之間的垂直空間。 我見過的所有解決方案似乎都為此提到了 iOS,但我想在 Mac OS 中執行此操作(它應該具有相同的行為,但事實並非如此)。

這是可能解決方案的演示(使用 Xcode 11.4 / macOS 10.15.6 測試)。

注意:如果需要有多個活動列表(即 NSTableView)並且其中一些應該有單元間距(也稱為分隔符),那么它們應該由 SwiftUI 儀器完成,因為這種方法會禁用所有可見列表的單元間距

演示

var body: some View {
    VStack {
        Text("Selected: \(selectedPerson ?? "<none>")")
        List(selection: $selectedPerson) {
             ForEach(persons, id: \.self) { person in
                Text(person)
             }
             .listRowBackground(Color.red)
             .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
        }.border(Color.green)
        .onReceive(NotificationCenter.default.publisher(for: NSView.frameDidChangeNotification)) {
            guard let tableView = $0.object as? NSTableView else { return }
            tableView.intercellSpacing = .zero
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM