我有一個簡單的 SwiftUI 應用程式,它會在每個點擊手勢上重新生成隨機背景并為其添加引號。
AsyncImage(url: URL(string: backgroundImgUrl)) { phase in
switch phase {
case .empty:
Color.purple.opacity(0.1)
case .success(let image):
image
.ignoresSafeArea()
.scaledToFit()
.onAppear {
//code here happen for 1 time only even for every background change
}
//can I execute code here??? syntax error happens
case .failure(_):
Image(systemName: "exclamationmark.icloud")
.resizable()
.scaledToFit()
@unknown default:
Image(systemName: "exclamationmark.icloud")
}
}
當我嘗試使用隨機點擊手勢添加引號時出現問題,它會在背景更新之前出現。所以我想在生成每個新的隨機背景時執行代碼,但我做不到。你能給我一些提示嗎?
onTapGesture 代碼:
.onTapGesture {
backgroundImgUrl = "https://source.unsplash.com/1600x900/?nature&\(Int.random(in: 1..<6236))"
}
uj5u.com熱心網友回復:
您可以嘗試使用以下方法onChange:
struct ContentView: View {
@State var backgroundImgUrl = "https://source.unsplash.com/1600x900/?nature&\(Int.random(in: 1..<6236))"
var body: some View {
AsyncImage(url: URL(string: backgroundImgUrl)) { phase in
switch phase {
case .empty:
Color.purple.opacity(0.1)
case .success(let image):
image
.ignoresSafeArea()
.scaledToFit()
.onChange(of: image) { _ in // <-- here
// code here happen for every image change
print("----> in onChange ")
}
case .failure(_):
Image(systemName: "exclamationmark.icloud")
.resizable()
.scaledToFit()
@unknown default:
Image(systemName: "exclamationmark.icloud")
}
}
.onTapGesture {
backgroundImgUrl = "https://source.unsplash.com/1600x900/?nature&\(Int.random(in: 1..<6236))"
}
}
}
uj5u.com熱心網友回復:
可以通過添加識別符號,例如
case .success(let image):
image
.ignoresSafeArea()
.scaledToFit()
.onAppear {
// this works
}
.id(backgroundImgUrl) // << here !! (tested Xcode 13.4 / iOS 15.5)
注意:插入新影像視圖并洗掉舊影像視圖時,可能會看到默認的不透明度過渡效果。如果不需要,可以通過添加 nil 影片來緩解它。
GitHub 上的測驗模塊
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/491681.html
