AsyncImage
AsyncImage
struct AsyncImage<Content> where Content : View
View
Overview
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:scale:content:placeholder:)
. 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 ProgressView
first, and then the image scaled to fit in the specified frame:
Important
You can’t apply image-specific modifiers, like resizable(capInsets:resizingMode:)
, directly to an AsyncImage
. 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:scale:transaction:content:)
initializer, which takes a content
closure that receives an AsyncImagePhase
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.
}
}
Topics
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)
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
2022-11-01 js判断数据类型
2022-11-01 杨涛
2022-11-01 Asp.Net MVC 中的 Cookie讲解
2021-11-01 Numeral.js实现千分位、补零、序数词缩写等
2021-11-01 Typescript中的as、问号与感叹号
2021-11-01 TypeScript 联合类型
2021-11-01 TypeScript学习笔记(八):Object对象类型