ios - UIStackView:我可以限制可以插入的视图以符合协议吗?
问题描述
除了让任何 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
}
}
推荐阅读
- python - Matplotlib 给出 This application failed to start because it could not find or load the Qt platform plugin "xcb" in ""
- python - 当原始引用现在指向一个新值时,Python 如何知道在哪里找到创建的不可变值?
- java - (Akka HTTP)当我将 .XLSX 文件作为 Array [bytes] 发送给用户时,用户会得到文件夹
- scala - 如何用元素 3,4 ,5 填充 scala 数组?
- mysql - 如何将一列设置为 MySQL 为先前设置的行生成的数字?
- jenkins - 如何从共享库修改 Jenkins 配置?
- workflow - 使用 FreeBSD 代码库的推荐工作流程和环境是什么?
- textview - SwiftUI 成为FirstResponder
- docker - 我可以将 Ubuntu Docker 直接部署到 EC2(不在 Ubuntu 内部)吗?
- c++ - 如何对类数组进行排序?