LoginSignup
0
3

SwiftUI List内でGeometryReaderを使用する方法

Posted at

List内でのGeometryReaderの問題

下のQiitaの画像を与えられたViewの横幅いっぱいに、正方形でList内で表示したい場合、そのまま適用するとViewが崩れてしまいます。

List {
  GeometryReader { geometry in
    AsyncImage(url: url) { image in
      image
        .resizable()
        .frame(
          width: geometry.size.width,
          height: geometry.size.width
        )
    } placeholder: {
      ProgressView()
    }
  }
}

解決方法

解決方法は簡単でscaleToFit()GeometryReaderに付与することです。
.aspectRatio(contentMode: .fit)でも可能です。

List {
  GeometryReader { geometry in
    AsyncImage(url: url) { image in
      image
        .resizable()
        .frame(
          width: geometry.size.width,
          height: geometry.size.width
        )
    } placeholder: {
      ProgressView()
    }
  }
  .scaledToFit() // ADD
  //.aspectRatio(contentMode: .fit) // こちらでも良い
}

より綺麗にする(番外編)

上のプレビューだと元の画像の横幅が広いため、横が圧縮されてしまっています。
綺麗に表示するために真ん中をクリップして、正方形で表示していきます。

.aspectRatio(contentMode: .fill)clipped()を使って正方形にクリップしています。

List {
  GeometryReader { geometry in
    AsyncImage(url: url) { image in
      image
        .resizable()
        .aspectRatio(contentMode: .fill)
        .frame(
          width: geometry.size.width,
          height: geometry.size.width
        )
        .clipped()
    } placeholder: {
      ProgressView()
    }
  }
  .aspectRatio(1, contentMode: .fit)
}

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3