SwiftUI - 如何使用异步操作更改同步值 [英] SwiftUI - How do I change a synchronous value using an asynchronous operation
问题描述
我有一张挂锁的图片,只有在 SwiftUI 上没有购买特定的应用内购买时才会显示该图片.
I have an image of a padlock that must only show if a particular inapp purchase was not purchased, on SwiftUI.
类似的东西
Image(systemName: "lock.circle.fill")
.renderingMode(.template)
.foregroundColor(.white)
.font(symbolFont)
.opacity(wasPurchased(item: item))
但据我所知wasPurchased
一定是同步函数吧?
But as far as I see wasPurchased
must be a synchronous function, right?
类似的东西
func wasPurchased(item: item) -> Bool {
return check(item:item) ? true : false
}
但是,这样的检查通常是通过网络异步发生的,而且在我看来,该函数必须具有像
But, such checks normally happen asynchronously, over the network, and the function, as I see, must have a signature like
func wasPurchased(item: item, runOnFinishChecking:(Bool)->()) {
我不知道如何使用异步来控制此类元素的不透明度.
I don't see how I can use something asynchronous to control the opacity of such element.
我该怎么做?
推荐答案
您可以使用状态属性(或视图模型中的一个)并更新该属性.
You can use state property for that (or one in view model) and update that property.
这是一个基于状态的演示:
Here is a demo based on state:
@State private var locked = true
...
Image(systemName: "lock.circle.fill")
.renderingMode(.template)
.foregroundColor(.white)
.font(symbolFont)
.opacity(self.locked ? 1 : 0)
.onAppear {
self.wasPurchased(self.item) { purchased in
DispatchQueue.main.async {
self.locked = !purchased
}
}
}
...
这篇关于SwiftUI - 如何使用异步操作更改同步值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!