0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift UI】iOS 15からAsyncImageでURL先の画像を読み込む

Posted at

はじめに

WWDC2021にリリースされたSwiftUIには、**AsyncImage**と呼ばれる新しいビルトインビューが導入されており、非同期で簡単にURLからリモート画像をダウンロードできるようになった。

環境: xcode13 beta5, iOS15

目次

  1. 基本的な書き方
  2. 画像読み込み中の時

基本的な書き方

ContentView.swift
struct ContentView: View {
    var logo: Logo

    var body: some View {
        VStack {
            AsyncImage(url: URL(string: logo.imageURL))
                .frame(maxWidth: 300, maxHeight: 100)
        }
    }
}

・**AsyncImageの書き方はとてもシンプルで、URLをつめれば非同期で画像を読み込みできる。
・ただ、リサイズしなければ画像はデフォルトのままになっちゃうので、Swift UIではよく
frame**を使って画像の加工をする。

画像読み込み中の時

・非同期処理のため、画像を読み込みの間に余白が出てしまい、なので画像が完全に読み込んだ前にインジゲーターなどのアイコンを用意する。
・今回のアイコンはアップルさんが用意した**"photo"**というSF Symbolsを使う。

ContentView.swift
@ViewBuilder
func placeholderImage() -> some View {
   Image(systemName: "photo")
       .renderingMode(.template)
       .resizable()
       .aspectRatio(contentMode: .fit)
       .frame(width: 200, height: 200)
       .foregroundColor(.gray)
}



・画面が読み込まれる時に、先にplaceholderにある**placeholderImage()**が読み込まれ、非同期処理が終わった後にlogoが表示される。

ContentView.swift
struct ContentView: View {
    var logo: Logo

    var body: some View {
        VStack {
            AsyncImage(url: URL(string: logo.imageURL)) { image in
                image
                  .frame(maxWidth: 300, maxHeight: 100)
            } placeholder: {
                  placeholderImage()
            }
        }
    }
}

参考文献

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?