I have a basic view controller subclass which contains a UIStackView and a UIButton. I want to run some code each time a view is added or removed from the stack view's arrangedSubviews
array using Combine. Here's is my failed attempt to do this:
import Combine
import UIKit
class ViewController: UIViewController {
@IBOutlet var stackView: UIStackView!
@IBOutlet var button: UIButton!
var cancelables = Set<AnyCancellable>()
override func viewDidLoad() {
super.viewDidLoad()
stackView.publisher(for: \.arrangedSubviews).sink { views in
button.isEnabled = views.count < 5
}
.store(in: &cancelables)
}
@IBAction func addTapped(_ sender: UIButton) {
let customView = CustomView()
stackView.addArrangedSubview(customView)
}
}
Each time I tap the button, a new view is added to the stack view, but the change to arrangedSubviews
is not published, which doesn't trigger the code in the sink
block. In the case above, the button is still enabled even if arrangedSubviews.count
is more than 5.
How can I fix this so that I can correctly publish changes whenever a new view is added or removed from the arrangedSubviews
array?
Thank you for any help.