[英]Constraint-based layout of images in a list in SwiftUI
我想在SwiftUI
List
中實現以下基於約束的圖像布局:
Image
的左/右邊緣固定到列表邊距(適應屏幕尺寸)我嘗試過但不起作用的方法(基於這篇文章):
struct MyView: View {
@ObservedObject var viewModel: MyViewModel
let aspectRatio = CGSize(width: 345, height: 120)
var body: some View {
List {
ForEach(viewModel.items) { item in
GeometryReader { geo in
Image("test_image")
.resizable()
.aspectRatio(aspectRatio, contentMode: .fill)
.frame(width: geo.size.width)
.clipped()
}
}
}
}
}
我在 iPhone 11 Pro 上從geo
獲得的尺寸是 (343, 32)。 寬度是有道理的,但由於某種原因,它不會讓單元格擴展超過 32 的高度。 歡迎任何提示,因為我真的開始懷念自動布局約束。
不需要使用GeometryReader
這樣的事情。 對於固定高度,您可以只提供一個僅具有height
的frame
。 您也不需要創建自己的let aspectRatio = CGSize(width: 345, height: 120)
- 如果您將其保留為 nil(默認情況下)應該沒問題。
編輯:使用padding
而不是帶間距的VStack
struct MyView: View {
var body: some View {
List {
ForEach(0..<10, id: \.self) { item in
Image("test_image")
.resizable()
.aspectRatio(contentMode: .fill) /// no need for custom aspect ratio
.frame(height: 120) /// fixed height of image
.clipped() /// stop image from overflowing
.padding(.vertical, 12) /// extra vertical padding
}
}
}
}
結果(帶有"test_image" ):
但是,它的高度固定為120
,因此圖像的頂部和底部都被裁剪掉了。 要解決此問題,您可以完全避免frame
和clipped
。
struct MyView: View {
var body: some View {
List {
ForEach(0..<10, id: \.self) { item in
Image("test_image")
.resizable()
.aspectRatio(contentMode: .fill) /// doesn't matter if it's fit or fill
.padding(.vertical, 12) /// extra vertical padding
}
}
}
}
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.