gpt4 book ai didi

ios - 从多个类swift继承的替代方法

转载 作者:搜寻专家 更新时间:2023-10-31 22:38:14 25 4
gpt4 key购买 nike

我有一个使用“框架”管理 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 类中的方法。我该怎么做呢? (我试过从两个类继承,没用)

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

谢谢你的帮助;)

最佳答案

实现此目的的一种方法是编写协议(protocol)扩展。因为你有属性,所以你需要实现一个组件,但应该不会太难 -

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()

关于ios - 从多个类swift继承的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52971202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com