gpt4 book ai didi

swift - 如何将 NSColorPanel 正确连接到服务器以避免过载

转载 作者:行者123 更新时间:2023-12-03 16:40:05 38 4
gpt4 key购买 nike

我正在使用 NSColorPanel 来更改 View 的颜色。此 View 的颜色也保存在数据库 (Firestore) 中。

import AppKit

class ColorPanel {

static var shared = ColorPanel()

private var stage: DB.Stage.Document? = nil

private let cp = NSColorPanel.shared

init() {
cp.setTarget(self)
cp.setAction(#selector(colorDidChange(sender:)))
cp.isContinuous = false
}

func show(stage: DB.Stage.Document) {
self.stage = stage
cp.makeKeyAndOrderFront(nil)
}

@objc func colorDidChange(sender: NSColorPanel) {
guard let stage = stage else { return }
stage.data?.color.red = Double(sender.color.redComponent)
stage.data?.color.green = Double(sender.color.greenComponent)
stage.data?.color.blue = Double(sender.color.blueComponent)
stage.update()
}
}

问题是我想将 isContinuos 设置为 true 以便看到我的 View 实时更改颜色,但向服务器发送了太多更新,因此我被迫将其设置为 false。

有办法解决这个问题吗?我只需要在完成拖动后进行更新,但我不知道如何进行。

附:要在 SwiftUI View 中调用 ColorPanel,我执行以下操作:

ColorPanel.shared.show(stage: stage)

最佳答案

请尝试我会使用的方法。 免责声明:由于缺少 Firestore 设置,未进行测试

import Combine

class ColorPanel {

static var shared = ColorPanel()

private var stage: DB.Stage.Document? = nil

private let cp = NSColorPanel.shared

private var subscriber: AnyCancellable?
private let publisher =
PassthroughSubject<NSColor, Never>()
.throttle(for: 10, scheduler: RunLoop.main, latest: true)

init() {
cp.setTarget(self)
cp.setAction(#selector(colorDidChange(sender:)))
cp.isContinuous = true
}

func show(stage: DB.Stage.Document) {
self.stage = stage
self.subscriber = nil

if stage != nil {
self.subscriber = self.publisher
.sink { _ in
self.stage.update() // << be called once per 10 seconds
}
}
cp.makeKeyAndOrderFront(nil)
}

@objc func colorDidChange(sender: NSColorPanel) {
guard let stage = stage else { return }
stage.data?.color.red = Double(sender.color.redComponent)
stage.data?.color.green = Double(sender.color.greenComponent)
stage.data?.color.blue = Double(sender.color.blueComponent)

self.publisher.upstream.send(sender.color)
}
}

关于swift - 如何将 NSColorPanel 正确连接到服务器以避免过载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59667482/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com