在 Combine 中点击发布者执行两次

Tap publisher execute twice in Combine

我不想使用 saveButton.addTarget(:selector:event) 这就是为什么 我尝试使用 CombineCocoa 框架中的 tap publisher,如下所示

 saveButton.tapPublisher.sink {  _ in
        print("tap") // tap twice
    }
    .store(in: &subscriptions)

当我点击 saveButton 然后 'tap' 打印两次。

我也尝试使用来自 Combine 框架

saveButton.publisher(for: .touchUpInside) 

但结果相同

我的代码在这里

class ArticleVC: UIViewController {
    let saveButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("Save", for: .normal)
        return btn
    }()
    
    var subscriptions: Set<AnyCancellable> = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // add to view
        view.addSubview(saveButton)
        didTapSave()
        saveButton.snp.makeConstraints {
            [=12=].centerX.centerY.equalToSuperview()
        }
        
        didTapSave()
    }
    
    func didTapSave() {
//        saveButton.tapPublisher.sink(receiveValue: { _ in
//            print("tap")  // twice printed 'tap'
//        })
//        .store(in: &subscriptions)
        /// OR
        saveButton.publisher(for: .touchUpInside).sink { _ in
            print("tap") // twice printed 'tap'
        }
        .store(in: &subscriptions)
    }
}

这是什么原因?

我的猜测是您创建了两次管道。但是您没有显示创建管道的位置,所以这只是一个猜测。 [编辑:在我发布这个答案之后,你在问题中发布了你的代码,我的猜测显然是正确的,因为我们现在可以 see 您创建了两次管道。]

为了支持这一点,我将展示我所做的:

import UIKit
import Combine
import CombineCocoa

class ViewController: UIViewController {
    @IBOutlet weak var button: UIButton!
    var storage = Set<AnyCancellable>()
    override func viewDidLoad() {
        super.viewDidLoad()
        button.tapPublisher
            .sink { _ in print("tap") }
            .store(in: &storage)
    }
}

这就是所有代码。我 运行 项目,我点击按钮,我看到“点击”一次。结束.