[英]How to remove extra empty cells in TableViewController, iOS - Swift
[英]Swift UI Remove Extra List Empty Cells without Navigation Controller
Swift 用戶界面 - Xcode
問題:當我的列表初始化時,我有額外的單元格。 但是,與其他帖子不同,我沒有導航視圖。 是否必須有一個 NavigationView 才能從我的列表中刪除多余的單元格。
我試圖實現一個導航視圖,但我不確定它是否是強制性的以及如何正確實現。
.navigationBarTitle("List")
.listStyle(GroupedListStyle())
我想在最后一個“當前”單元格的正下方開始一個新的文本或 UIButton,沒有額外的空格。
var body: some View {
VStack(alignment: .leading) {
Image("covidImage")
.resizable()
.aspectRatio(contentMode: .fit)
.cornerRadius(5)
Text("COVID DATA")
.font(.system(.title, design: .rounded))
.bold()
.lineLimit(3)
.padding(.bottom, 3)
.padding(.leading, 10)
Text("Represented by Sate in the United States")
.font(.subheadline)
.foregroundColor(.secondary)
.padding(.leading, 10)
.padding(.bottom, 0)
Text("Current State: CA")
.font(.subheadline)
.foregroundColor(.secondary)
.padding(.leading, 10)
.padding(.bottom, 10)
//List to Initialize TableView Data
List(covid) { covidData in
Image(systemName: "photo")
.padding()
HStack {
Text(covidData.dataTitle).frame(maxWidth: .infinity, alignment: .leading)
Text(covidData.dataValue)
.font(.subheadline)
.frame(maxWidth: .infinity, alignment: .trailing)
//.color(.gray)
}
}//END List
}//END Original VStack
}//END Some View
它們不是空單元格。 List
僅填充所有可用空間並在沒有內容的地方繪制空行占位符。 在您的場景中,需要將List
的高度限制為其內容。
這是一個解決方案。 使用 Xcode 11.4 / iOS 13.4 測試
為了更好的可見性,讓我們將您的列表分成自己的名為CovidDataList
的視圖,然后在您提供的body
中:
//List to Initialize TableView Data
CovidDataList(covid: self.covid)
}//END List
注意 1:列表的高度在運行時更新,因此應在運行的應用程序中進行測試(而不是在預覽中)
注 2:我使用復制的封面數據 model 進行了測試,因此您的代碼可能需要進行一些調整
struct CovidDataList: View {
@Environment(\.defaultMinListRowHeight) var minRowHeight
let covid: [CovidData]
@State private var listHeight = CGFloat.infinity
var body: some View {
List {
ForEach(covid, id: \.self) { covidData in
HStack {
Image(systemName: "photo")
.padding()
HStack {
Text("Title").frame(maxWidth: .infinity, alignment: .leading)
Text("Value")
.font(.subheadline)
.frame(maxWidth: .infinity, alignment: .trailing)
}
}
.listRowInsets(EdgeInsets()).padding(.horizontal)
}
.anchorPreference(key: BoundsPreferenceKey.self, value: .bounds) { [$0] }
}
.backgroundPreferenceValue(BoundsPreferenceKey.self) { rects in
GeometryReader { gp in
self.updateListFrame(gp: gp, anchors: rects)
}
}.frame(maxHeight: listHeight)
}
private func updateListFrame(gp: GeometryProxy, anchors: [Anchor<CGRect>]) -> some View {
let contentHeight = anchors.reduce(CGFloat.zero) { $0 + gp[$1].size.height }
DispatchQueue.main.async { // << required !!
self.listHeight = max(contentHeight, self.minRowHeight * CGFloat(self.covid.count))
}
return Color.clear
}
}
注意: BoundsPreferenceKey
取自this my answer
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.