我有this个上一个问题可以正确回答。这种情况是界面中某处的图像。
我也有相同问题的另一个变体,但是现在图像在列表单元格内。
该图像显示了一个挂锁,只有在未购买特定的inapp购买时,才必须在SwiftUI上显示。
类似
Image(systemName: "lock.circle.fill")
.renderingMode(.template)
.foregroundColor(.white)
.font(symbolFont)
.opacity(wasPurchased(item: item))
但是据我所知wasPurchased
必须是同步函数,对吧?
类似
func wasPurchased(item: item) -> Bool {
return check(item:item) ? true : false
}
但是,这样的检查通常是通过网络异步进行的,而且我所看到的功能必须具有类似的签名
func wasPurchased(item: item, runOnFinishChecking:(Bool)->()) {
该列表是从Core Data填充的,就像这样
@FetchRequest(fetchRequest: Expressao.getAllItemsRequest())
private var allItems: FetchedResults<Expressao>
var body: some View {
List {
ForEach(allItems, id: \.self) { item in
HStack {
Text(item.term)
.font(fontItems)
.foregroundColor(.white)
Image(systemName: "lock.circle.fill")
.renderingMode(.template)
.foregroundColor(.white)
.font(symbolFont)
.opacity(wasPurchased(item: item))
}
}
}
}
当整个对象都是数组时,我看不到如何使用异步方法来控制此类元素的不透明度。
我该怎么做?
答案 0 :(得分:1)
只需将行内容分为独立视图并采用上一篇文章中的方法即可。
var body: some View {
List {
ForEach(allItems, id: \.self) {
ExpressaoRowView(item: $0)
}
}
}
...
struct ExpressaoRowView: View {
@ObservedObject var item: Expressao
@State private var locked = true
var body: some View {
HStack {
Text(item.term)
.font(fontItems)
.foregroundColor(.white)
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
}
}
}
}
}
注意:您甚至可以将wasPurchased
检查器放置在外部(在父级或某些助手中)并作为属性注入ExpressaoRowView