不是让任何UIView插入UIStackView中,我可以对其进行设置,以便仅插入符合自定义协议(例如'MyProtocol')的视图吗?
您可以继承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
}
}