-1

Instead of letting any UIView be inserted into a UIStackView, can I set it so that only views which conform to a custom protocol, say 'MyProtocol' can be inserted?

Bilbo Baggins
  • 3,644
  • 8
  • 40
  • 64

1 Answers1

0

You could subclass uiview and make it accept the view and the protocol (from swift 4+, see https://stackoverflow.com/a/45276465/8517882)

It would look something like this:

protocol SomeProtocol {
    func someFunc()
}

class CustomStack: UIView {

    private let stack = UIStackView()

    init() {
        super.init(frame: CGRect.zero)
        self.addSubview(stack)
        // then you can constraint the stack to self
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }



    func addSubview(_ view: UIView & SomeProtocol) {
        self.stack.addSubview(view)
        view.someFunc() // you can call the protocol methods on the view

    }

    func addArrangedSubviews(_ view: UIView & SomeProtocol) {
        stack.addArrangedSubview(view)
        view.someFunc() // you can call the protocol methods on the view
    }

}

Enricoza
  • 1,101
  • 6
  • 18