我希望能够将百分比值传递给 CGRect
我创建了一个百分比类来获取输入,然后创建了四个值(x、y、宽度、高度)
现在我需要为 CGRect 创建一个扩展,以便能够使用其中的百分比值。扩展程序返回错误。
extension CGRect {
init(x: Percentage, y: Percentage, width: Percentage, height: Percentage) {
self.init(x: Percentage.x, y: Percentage.y, width: Percentage.width, height: Percentage.height)
ERROR: Instance member 'x' cannot be used on type 'Percentage'
}
}
class Percentage {
let x: CGFloat
let y: CGFloat
let width: CGFloat
let height: CGFloat
init(_ value: CGFloat) {
self.x = UIScreen.main.bounds.width * value
self.y = UIScreen.main.bounds.height * value
self.width = UIScreen.main.bounds.width * value
self.height = UIScreen.main.bounds.height * value
}
}
感谢您的帮助;)
编辑:
我希望能够像这样使用它:
CGRect(x: Percentage(0.5), y: 50, width: 100, height: 100)
最佳答案
Instance member 'x' cannot be used on type 'Percentage'
您正在使用类的类型,因此即使您在参数 percentage
中有,它也不会工作。
但如果您只是将某些 Percentage
作为 init
的参数传递,然后使用它的属性(与小的 p
一起使用,因为你需要初始化参数,而不是你的类类型)
init(percentage: Percentage) {
self.init(x: percentage.x, y: percentage.y, width: percentage.width, height: percentage.height)
}
在你编辑之后,我不得不说你不必使用自定义初始化,你可以只传递你的 Percentage
的属性
CGRect(x: yourPercentage.x, y: 50, ...)
关于ios - 将可能的输入类型添加到 CGRect Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53777466/