ios - 将可能的输入类型添加到 CGRect Swift

标签 ios swift class

我希望能够将百分比值传递给 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/

相关文章:

iphone - 动态插入更多 UITextFields

ios - 在单元测试中手动向左滑动以调用处理程序以在 Swift 中进行测试

ios - UIButton 随键盘一起移动。当用户按下一个键时位置重置

ios - 导航栏中的图像不会按比例缩小

c++ - 可以在类中使用 fstream 对象吗?

iOS - 推送通知在辞职的 IPA 中不起作用

android - 是否可以创建一个应用程序,安装后用户可以通过双击主页按钮轻松打开和关闭蓝牙/NFC?

ios - 设置内容插入使 UItableView 滚动一点

python - Pandas DataFrame 的组合与子类

jquery - 发现任何元素是否具有 jQuery 中的任何类