首页 > 解决方案 > UIStackView:我可以限制可以插入的视图以符合协议吗?

问题描述

除了让任何 UIView 插入 UIStackView 之外,我可以设置它以便只插入符合自定义协议的视图,比如“MyProtocol”吗?

标签: iosswiftuistackview

解决方案


您可以继承 uiview 并使其接受视图和协议(来自 swift 4+,请参阅https://stackoverflow.com/a/45276465/8517882

它看起来像这样:

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
    }

}


推荐阅读