【问题标题】:How to call subclass method from superclass with protocol conformance如何从具有协议一致性的超类调用子类方法
【发布时间】: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


【解决方案1】:

您可以在您的 CustomView 和 SomeProtocol 之间添加间接类,我们将其命名为 CustomViewBase。这个类应该继承 UIView 并实现 SomeProtocol。现在让您的类 CustomView 成为 CustomViewBase 的子类,并向其添加 add() 方法的实现并从中调用 super.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 CustomViewBase: UIView, SomeProtocol {
    var property: Int = 1
}

class CustomView: CustomViewBase {
    func add() {
        super.add()
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        print("CustomView.layoutSubviews 2")
        // 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
    override func add() {
        property += 10
        print("SubClassView.add [property: \(property)]")
    }
}

let view = SubClassView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

【讨论】:

    【解决方案2】:

    首先,让我们将所有的动画内容移到它自己的东西中。

    struct CustomAnimator {
        var touchesBegan: (UIView) -> Void = { $0.backgroundColor = .red() }
        var touchesEnded: (UIView) -> Void = { $0.backgroundColor = .clear() }
    }
    

    所以这就是我们想要动画的方式。当触摸开始时,我们会将它们变为红色。当接触结束时,我们会让它们变得清晰。这只是一个例子,当然可以被覆盖;这些只是默认值。这对你来说可能不是最方便的数据结构;你可以想出很多其他方法来存储它。但关键是它只是一个结构,它可以为它传递的东西设置动画。这不是一个视图本身。没有子类化。这只是一个值。

    那么,我们如何使用它呢?在子类化方便的情况下,我们可以这样使用:

    class CustomDownButton: UIButton {
        var customAnimator: CustomAnimator?
    
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            customAnimator?.touchesBegan(self)
            super.touchesBegan(touches, with: event)
        }
    
        override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
            customAnimator?.touchesEnded(self)
            super.touchesEnded(touches, with: event)
        }
    }
    

    因此,如果您想对视图进行子类化,只需为其分配一个 CustomAnimator 即可。但这并不是真正有趣的案例,IMO。有趣的情况是子类化不方便。我们想把它附加到一个普通按钮上。

    UIKit 已经为我们提供了一个工具,可以将触摸行为附加到随机视图,而无需对其进行子类化。它被称为手势识别器。因此,让我们构建一个来处理我们的动画:

    class CustomAnimatorGestureRecognizer: UIGestureRecognizer {
        let customAnimator: CustomAnimator
    
        init(customAnimator: CustomAnimator) {
            self.customAnimator = customAnimator
            super.init(target: nil, action: nil)
        }
    
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
            if let view = view {
                customAnimator.touchesBegan(view)
            }
            super.touchesBegan(touches, with: event)
        }
    
        override func reset() {
            // I'm a bit surprised this isn't in the default impl.
            if self.state == .possible {
                self.state = .failed
            }
            super.reset()
        }
    
        override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
            if let view = view {
                customAnimator.touchesEnded(view)
            }
            self.reset()
            super.touchesEnded(touches, with: event)
        }
    }
    

    这应该是很明显的。它只是在触摸开始或停止时调用动画师来修改我们的视图。正确处理状态机需要一点点簿记,但这非常简单。

    没有第三步。设置这个很简单:

    override func viewDidLoad() {
        super.viewDidLoad()
        customButton.customAnimator = CustomAnimator()
        normalButton.addGestureRecognizer(CustomAnimatorGestureRecognizer(customAnimator: CustomAnimator()))
    }
    

    GitHub 上的完整项目。

    【讨论】:

    【解决方案3】:

    我玩这个,我想出了两种不同的方法。 (带操场的 github -> https://github.com/nonameplum/Swift-POP-with-Inheritance-problem)

    1. 作曲
    struct BaseFunctionality<T: UIView where T: SomeProtocol> {
        var add: (T) -> Void
        init() {
            add = { (view) in
                view.property += Int(view.frame.width)
                print("BaseFunctionality [property: \(view.property)]")
            }
        }
    }
    
    protocol SomeProtocol: class {
        var property: Int { get set }
    }
    
    class CustomView: UIView, SomeProtocol {
        var property: Int = 1
        var baseFunc = BaseFunctionality<CustomView>()
    
        override func layoutSubviews() {
            super.layoutSubviews()
            print("CustomView.layoutSubviews")
            // Some specific high end code for CustomView
            baseFunc.add(self)
        }
    }
    
    class CustomCollectionViewCell: UICollectionViewCell, SomeProtocol {
        var property: Int = 2
        var baseFunc = BaseFunctionality<CustomCollectionViewCell>()
    
        override func layoutSubviews() {
            super.layoutSubviews()
            print("CustomCollectionViewCell.layoutSubviews")
            // Some specific high end code for CustomCollectionViewCell
            baseFunc.add(self)
        }
    
    }
    
    class SubClassView: CustomView { // Class that can implemented by the third party developer for customisation
    
        override init(frame: CGRect) {
            super.init(frame: frame)
    
            self.baseFunc.add = { (view) in
                view.property -= Int(view.frame.width)
                print("SubClassView [property: \(view.property)]")
            }
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
    }
    
    let view = SubClassView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    
    1. 代表类型
    protocol Functionality: class {
        func add()
    }
    
    // Default implementation
    extension SomeProtocol where Self: UIView {
        func add() {
            property = -5
            print("Functionality.add [property = \(property)]")
        }
    }
    
    protocol SomeProtocol: class {
        var property: Int { get set }
        var delegate: Functionality? { get set }
    }
    
    class CustomView: UIView, SomeProtocol {
        var property: Int = 1
        weak var delegate: Functionality?
    
        override func layoutSubviews() {
            super.layoutSubviews()
            print("CustomView.layoutSubviews")
            // Some specific high end code for CustomView
            if let delegate = delegate {
                delegate.add()
            } else {
                self.add()
            }
        }
    }
    
    class CustomCollectionViewCell: UICollectionViewCell, SomeProtocol {
        var property: Int = 2
        weak var delegate: Functionality?
    
        override func layoutSubviews() {
            super.layoutSubviews()
            print("CustomCollectionViewCell.layoutSubviews")
            // Some specific high end code for CustomCollectionViewCell
            if let delegate = delegate {
                delegate.add()
            } else {
                self.add()
            }
        }
    }
    
    class SubClassView: CustomView { // Class that can implemented by the third party developer for customisation
        override init(frame: CGRect) {
            super.init(frame: frame)
            self.delegate = self
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    
    extension SubClassView: Functionality {
        func add() {
            property = 5
            print("SubClassView.add [property = \(property)]")
        }
        func doNothing() { print("SubClassView.doNothing [\(property)]") }
    }
    
    let view = SubClassView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      • 2023-04-05
      • 2011-10-24
      • 2012-04-18
      相关资源
      最近更新 更多