簡體   English   中英

SwiftUI 列表中基於約束的圖像布局

[英]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這樣的事情。 對於固定高度,您可以只提供一個僅具有heightframe 您也不需要創建自己的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 ,因此圖像的頂部和底部都被裁剪掉了。 要解決此問題,您可以完全避免frameclipped

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.

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