【发布时间】:2021-06-22 11:30:48
【问题描述】:
首先,我对 swift 和编程非常陌生(来自设计领域)。 我正在尝试根据 posts.count 更新 doesNotificationsExist
我在Api().getPosts {} 中变得真实
我在哪里打印以下内容:
print("Api().getPosts")
print(doesNotificationExist)
但在外面(在loadData() {})我仍然得到错误而不是@Publihed var doesNotificationExist:Bool = false 不会更新。
请帮帮我,我真的很感激一些关于我做错了什么以及我需要做什么的指导。
这是我的代码:
import SwiftUI
import Combine
public class DataStore: ObservableObject {
@Published var posts: [Post] = []
@Published var doesNotificationExist:Bool = false
init() {
loadData()
startApiWatch()
}
func loadData() {
Api().getPosts { [self] (posts) in
self.posts = posts
if posts.count >= 1 {
doesNotificationExist = true
}
else {
doesNotificationExist = false
}
print("Api().getPosts")
print(doesNotificationExist)
}
print("loadData")
print(doesNotificationExist)
}
func startApiWatch() {
Timer.scheduledTimer(withTimeInterval: 60, repeats: true) {_ in
self.loadData()
}
}
查看我尝试根据store.doesNotificationsExist设置图像的位置
状态栏控制器:
import AppKit
import SwiftUI
class StatusBarController {
private var statusBar: NSStatusBar
private var statusItem: NSStatusItem
private var popover: NSPopover
@ObservedObject var store = DataStore()
init(_ popover: NSPopover)
{
self.popover = popover
statusBar = NSStatusBar.init()
statusItem = statusBar.statusItem(withLength: 28.0)
statusItem.button?.action = #selector(togglePopover(sender:))
statusItem.button?.target = self
if let statusBarButton = statusItem.button {
let itemImage = NSImage(named: store.doesNotificationExist ? "StatusItemImageNotification" : "StatusItemImage")
statusBarButton.image = itemImage
statusBarButton.image?.size = NSSize(width: 18.0, height: 18.0)
statusBarButton.image?.isTemplate = true
statusBarButton.action = #selector(togglePopover(sender:))
statusBarButton.target = self
}
}
`Other none relevant code for the question`
}
【问题讨论】:
标签: swift swiftui observableobject