SwiftUI-如何在列表单元格中使用异步操作更改同步值
我已经正确回答了前面的问题。这种情况是界面中某个位置的图像 我有另一个相同问题的变体,但现在图像位于列表单元格中 该图显示了一个挂锁,该挂锁必须仅在SwiftUI上显示未购买特定inapp的情况 差不多SwiftUI-如何在列表单元格中使用异步操作更改同步值,swift,swiftui,Swift,Swiftui,我已经正确回答了前面的问题。这种情况是界面中某个位置的图像 我有另一个相同问题的变体,但现在图像位于列表单元格中 该图显示了一个挂锁,该挂锁必须仅在SwiftUI上显示未购买特定inapp的情况 差不多 Image(systemName: "lock.circle.fill") .renderingMode(.template) .foregroundColor(.white) .font(symbolFont) .opacity(wasP
Image(systemName: "lock.circle.fill")
.renderingMode(.template)
.foregroundColor(.white)
.font(symbolFont)
.opacity(wasPurchased(item: item))
func wasPurchased(item: item) -> Bool {
return check(item:item) ? true : false
}
但据我所知,是购买的
必须是一个同步函数,对吗
差不多
Image(systemName: "lock.circle.fill")
.renderingMode(.template)
.foregroundColor(.white)
.font(symbolFont)
.opacity(wasPurchased(item: item))
func wasPurchased(item: item) -> Bool {
return check(item:item) ? true : false
}
但是,这样的检查通常是通过网络异步进行的,正如我看到的,函数必须有一个签名,如
func wasPurchased(item: item, runOnFinishChecking:(Bool)->()) {
该列表由核心数据填充,如下所示
@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))
}
}
}
}
@FetchRequest(FetchRequest:Expressao.getAllItemsRequest())
私有变量allItems:FetchedResults
var body:一些观点{
名单{
ForEach(allItems,id:\.self){item in
HStack{
案文(项目.期限)
.font(字体项目)
.foregroundColor(.白色)
图像(系统名称:“锁定.圆圈.填充”)
.renderingMode(.template)
.foregroundColor(.白色)
.font(symbolFont)
.不透明度(已购买(项目:项目))
}
}
}
}
我不知道当整个元素是一个数组时,如何使用异步的东西来控制这样的元素的不透明度
如何做到这一点?只需将行内容分离为独立视图,并应用上一篇文章中的方法即可
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
}
}
}
}
}
注意:您甚至可以将
waspowered
checker放在外面的某个地方(在父级或某个助手中),并将其作为属性注入ExpressaoRowView
我现在看到了!谢谢这个快捷界面对我来说是新的,我的大脑仍然难以理解它。特别是在使用其他语言编程20年后,12年使用Objective-C,5年使用swift。天哪!谢谢