【发布时间】:2016-06-20 21:04:23
【问题描述】:
我正在创建 swift UI 组件,它将为 UIView 和 UICollectionViewCell 提供一些功能。我想让定制变得容易。 (这里的代码当然是简化的)在下面的代码中,我将在layoutSubview 中做一些艰苦的工作(我必须为每个自定义类覆盖layoutSubviews,因为在扩展中我们不能覆盖类方法)然后调用@ 987654324@ 具有默认实现的方法,如果需要,应该很容易更改其行为。
问题是创建SubClassView 实例正确调用CustomView.layoutSubviews,但在此方法内部调用扩展名SomeProtocol.add 而不是SubClassView.add。我知道这是由 Swift 设计的,但是如何在不覆盖我为他准备的 layoutSubviews 的情况下实现我的组件的开发人员,只覆盖我为自定义准备的一个 add 方法,默认实现为他准备好了,如果他没有兴趣改变它。
protocol SomeProtocol: class {
var property: Int { get set }
func add() // Method that can be override for custom behaviour
}
extension SomeProtocol where Self: UIView {
// Default implementation
func add() {
property += Int(frame.width)
print("SomeProtocol.add [property: \(property)]")
}
}
class CustomView: UIView, SomeProtocol {
var property: Int = 1
override func layoutSubviews() {
super.layoutSubviews()
print("CustomView.layoutSubviews")
// Some specific high end code for CustomView
add()
}
}
class CustomCollectionViewCell: UICollectionViewCell, SomeProtocol {
var property: Int = 2
override func layoutSubviews() {
super.layoutSubviews()
print("CustomCollectionViewCell.layoutSubviews")
// Some specific high end code for CustomCollectionViewCell
add()
}
}
class SubClassView: CustomView { // Class that can implemented by the third party developer for customisation
// This method will not be called
func add() {
property += 10
print("SubClassView.add [property: \(property)]")
}
}
let view = SubClassView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
// prints:
// CustomView.layoutSubviews
// SomeProtocol.add [property: 101]
【问题讨论】:
-
这几乎是最新的 WWDC 谈话,UIKit 应用程序中的面向协议和价值的编程中示例的前提:developer.apple.com/videos/play/wwdc2016/419 看看他们的布局协议,看看是否是适合您案例的工具。
-
我很快看了这个演讲,似乎我们应该使用组合范式。但我不知道如何在我的情况下使用它。
-
你能详细介绍一下真正的目标吗?您已经将其表达为一个抽象的子类化问题,因此很难设计一个不基于子类化的解决方案。 “property”和“add”很有可能是错误的起点。
-
@RobNapier 目标是我想覆盖一些基本的 UIKit 类,如 UIKit 以提供易于调整的基本功能,例如,对于覆盖的 pressesBegan 方法,我想提供默认动画。在 pressesBegan 内部,我可以检查控件的状态、更改它并根据情况调用我的方法 pressAnimation(),该方法在扩展中实现以提供默认行为,并且应该易于开发人员自定义。一个问题是我无法在 UIView 的扩展中覆盖 pressesBegan ...
-
... 所以我需要分别对每个 UIKit 类进行子类化(这就是我尝试使用扩展来提供默认行为以避免重复代码的原因)。第二个问题:如果开发者覆盖我的 pressesBegan 并调用 super 然后提供自定义动画,他将添加可能导致问题的第二个动画。
标签: ios swift inheritance swift2 swift-protocols