【发布时间】:2020-05-25 11:19:10
【问题描述】:
所以我有一个 ViewController 有一个类型为“Something”的属性,这个相同的视图控制器我想将它与类型为“something1”的不同属性一起使用,我正在考虑为每个自定义类型“something”制定一个协议" 和 "something1" 并且它们会在 ViewController 中提供我需要的东西,但它们都是结构,并且它们都不起作用,因为它们都是值类型。
我的示例代码如下:
final class DynamicViewController: UIViewController {
private let attribute: CustomType // something or Somthing1
private let stackView: UIStackView
init(attribute: CustomType) {
self.attribute = attribute
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
private func setupViews() {
let scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scrollView)
NSLayoutConstraint.activate ([
...
])
scrollView.addSubview(stackView)
NSLayoutConstraint.activate([
...
])
getInfoLabels()
}
private func getInfoLabels() {
if let attribute = attribute {
numerateInObjectAndGetLabel(obj: attribute)
}
}
private func numerateInObjectAndGetLabel(obj: Any) {
let mirroredAttr = Mirror(reflecting: obj)
for (_, attr) in mirroredAttr.children.enumerated() {
if let txts = attr.value as? [String] {
for txt in txts {
stackView.addArrangedSubview(getLabel(for: txt))
}
}
}
}
private func getLabel(for text: String) -> UILabel {
let label = UILabel()
....
return label
}}
我确实有使用多种自定义类型制作多个可选属性的解决方案,但在我的情况下,我有超过 10 种自定义类型,所以它会变得丑陋..
有没有办法用简洁干净的方法解决这个问题?我真的不喜欢冗余代码。
【问题讨论】:
标签: ios swift generics dynamic swift-protocols