【问题标题】:Alternative to Inheritance from multiple classes swift从多个类继承的替代方法 swift
【发布时间】:2018-10-25 15:52:47
【问题描述】:

我有一个使用“框架”管理 UIKit 元素定位的类:

class EasyPos: UIView {
    var screenWidth = UIScreen.main.bounds.width
    var screenHeight = UIScreen.main.bounds.height

    var x: CGFloat = 0          { didSet { self.updateFrame() } }
    var y: CGFloat = 0          { didSet { self.updateFrame() } }
    var width: CGFloat = 0      { didSet { self.updateFrame() } }
    var height: CGFloat = 0     { didSet { self.updateFrame() } }

    func updateFrame() {
        frame = CGRect(x: x, y: y, width: width, height: height)

        if x < 0 {
            frame = CGRect(x: screenWidth - abs(x) - width, y: frame.minY, width: frame.width, height: frame.height)
        }
        if y < 0 {
            frame = CGRect(x: frame.minX, y: screenHeight - abs(y) - height, width: frame.width, height: frame.height)
        }
    }

    required init(x: CGFloat = 0, y: CGFloat = 0, width: CGFloat = 40, height: CGFloat = 40) {

        self.x = x
        self.y = y
        self.width = width
        self.height = height

        super.init(frame: .zero)

        updateFrame()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

现在我想添加一个继承自 UIbutton 的类和一个继承自 UILabel 的类。他们都应该能够使用 EasyPos 类中的方法。我该怎么做呢? (我试过从两个类继承,没用)

我知道这与协议有关。但我也无法让它工作。

感谢您的帮助;)

【问题讨论】:

  • UIView创建一个extension..

标签: ios swift class uikit


【解决方案1】:

您可以这样做的一种方法是编写协议扩展。因为你有属性,所以你需要实现一个组件,但这应该不会太难 -

struct FrameComponent {
    var x: CGFloat = 0         
    var y: CGFloat = 0          
    var width: CGFloat = 0      
    var height: CGFloat = 0
}

protocol EasyPos {
    var fc: FrameComponent { get, set }
    func updateFrame()
}

extension EasyPos where Self: UIView {
     func updateFrame() {
        frame = CGRect(x: fc.x, y: fc.y, width: fc.width, height: fc.height)

        if fc.x < 0 {
            frame = CGRect(x: screenWidth - abs(fc.x) - fc.width, y: frame.minY, width: 
              frame.width, height: frame.height)
        }
        if fc.y < 0 {
            frame = CGRect(x: frame.minX, y: screenHeight - abs(fc.y) - fc.height, width: 
              frame.width, height: frame.height)
        }
    }
}

你应该记住的是扩展不能添加属性观察者,所以你需要手动调用updateFrame()

【讨论】:

  • 当我将“var fc: FrameComponent { didSet { update() } }”添加到我的类中时,它不会工作,因为:“属性‘self.fc’未在 super.init 调用时初始化”。你能帮我在课堂上实施你的解决方案吗?
  • 无需通过制作 FrameComponent 结构来重新发明 CGRect。
  • 谢谢,我只需在类中添加“var fc: FrameComponent = FrameComponent() { didSet { updateFrame() } }”就可以让它工作
  • 是的,很抱歉同意@CodeBender
猜你喜欢
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 2013-05-20
  • 1970-01-01
  • 2013-06-18
  • 2017-07-26
  • 1970-01-01
  • 2014-10-09
相关资源
最近更新 更多