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

问题描述 投票:1回答:1

我正在使用NSColorPanel更改视图的颜色。该视图的颜色也保存在数据库(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以便看到视图实时更改颜色,但是正在向服务器发送太多更新,因此我被迫将其设置为false。

有解决此问题的方法吗?完成拖动后,我只需要进行更新即可,但我不知道如何。

ps.s。要在我的SwiftUI视图中调用ColorPanel,请执行以下操作:

ColorPanel.shared.show(stage: stage)
swift cocoa swiftui appkit nscolorpanel
1个回答
0
投票

请尝试一种我会使用的方法。 免责声明:由于缺少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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.