【SwiftUI】LazyVGrid 画像の一覧
前回LazyVGridを取り上げましたが、今回は画像の一覧を、appcodaさんのサイトのコードを引用して表示してみます。
1.列表示
1) スクリーンショット
2) コード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Photo: Identifiable { | |
var id = UUID() | |
var name: String | |
} | |
let samplePhotos = (1...20).map { Photo(name: "coffee-\($0)") } | |
struct ContentView: View { | |
@State var gridLayout: [GridItem] = [ GridItem() ] | |
var body: some View { | |
ScrollView { | |
LazyVGrid(columns: gridLayout, alignment: .center, spacing: 10) { | |
ForEach(samplePhotos.indices) { index in | |
Image(samplePhotos[index].name) | |
.resizable() | |
.aspectRatio(contentMode: .fit) | |
.cornerRadius(10) | |
.shadow(color: Color.primary.opacity(0.3), radius: 1) | |
} | |
} | |
} | |
} | |
} |
2.列表示
1) スクリーンショット
2) コード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Photo: Identifiable { | |
var id = UUID() | |
var name: String | |
} | |
let samplePhotos = (1...20).map { Photo(name: "coffee-\($0)") } | |
struct ContentView: View { | |
@State var gridLayout = Array(repeating: GridItem(), count: 2) | |
var body: some View { | |
ScrollView { | |
LazyVGrid(columns: gridLayout, alignment: .center, spacing: 10) { | |
ForEach(samplePhotos.indices) { index in | |
Image(samplePhotos[index].name) | |
.resizable() | |
.scaledToFill() | |
.frame(minWidth: 0, maxWidth: .infinity) | |
.frame(maxHeight: 150) | |
.cornerRadius(10) | |
.shadow(color: Color.primary.opacity(0.3), radius: 1) | |
} | |
} | |
} | |
} | |
} |
2.列表示 - pinterest風なレイアウト
2021年4月時点で探してみましたが、下記のようなピンタレスト風のレイアウトは組む場合は、SwiftUIのみでは難しいようです。UIViewRepresentableを利用するか、外部ライブラリを利用する方法しかなさそうです。
@temokiさんがQiitaでも記載されてます。今後、何か情報をキャッチアップしたら更新予定です。
![]() |