init(url: URL?, scale: CGFloat)
init<I, P>(url: URL?, scale: CGFloat, content: (Image) -> I, placeholder: () -> P)
Availability 有効性
Technology
struct AsyncImage<Content> where Content : View
This view uses the shared URLSession
instance to load an image from the specified URL, and then display it. For example, you can display an icon that’s stored on a server:
AsyncImage(url: URL(string: "https://example.com/icon.png"))
.frame(width: 200, height: 200)
Until the image loads, the view displays a standard placeholder that fills the available space. After the load completes successfully, the view updates to display the image. In the example above, the icon is smaller than the frame, and so appears smaller than the placeholder.
You can specify a custom placeholder using init(url:
. With this initializer, you can also use the content
parameter to manipulate the loaded image. For example, you can add a modifier to make the loaded image resizable:
AsyncImage(url: URL(string: "https://example.com/icon.png")) { image in
image.resizable()
} placeholder: {
ProgressView()
}
.frame(width: 50, height: 50)
For this example, SwiftUI shows a Progress
first, and then the image scaled to fit in the specified frame:
Important 重要
You can’t apply image-specific modifiers, like resizable(cap
, directly to an Async
. Instead, apply them to the Image
instance that your content
closure gets when defining the view’s appearance.
To gain more control over the loading process, use the init(url:
initializer, which takes a content
closure that receives an Async
to indicate the state of the loading operation. Return a view that’s appropriate for the current phase:
AsyncImage(url: URL(string: "https://example.com/icon.png")) { phase in
if let image = phase.image {
image // Displays the loaded image.
} else if phase.error != nil {
Color.red // Indicates an error.
} else {
Color.blue // Acts as a placeholder.
}
}
init(url: URL?, scale: CGFloat)
init<I, P>(url: URL?, scale: CGFloat, content: (Image) -> I, placeholder: () -> P)
init(url: URL?, scale: CGFloat, transaction: Transaction, content: (AsyncImagePhase ) -> Content)
var body: some View
typealias Body
enum AsyncImagePhase