【问题标题】:swift lazy var use let constantswift lazy var 使用 let 常量
【发布时间】:2016-03-11 22:37:18
【问题描述】:

我有很多相同size 的按钮,我想从惰性变量中设置恒定宽度,我应该怎么做? JRTopView.buttonWidthbuttonWidth 都不起作用。

  class JRTopView: UIView {
        let buttonWidth:CGFloat = 150
        lazy var leftButton: UIButton! = {
            let btn = UIButton(type: UIButtonType.Custom)
            btn.backgroundColor = UIColor.greenColor()
            btn.frame = CGRectMake(-30, 30, JRTopView.buttonWidth, buttonWidth)
            return btn
        }()
        lazy var rightButton: UIButton! = {
            let btn = UIButton(type: UIButtonType.Custom)
            btn.backgroundColor = UIColor.greenColor()
            btn.frame = CGRectMake(-30, 30, JRTopView.buttonWidth, buttonWidth)
            return btn
        }()
    }

谢谢!

编辑: 有趣的是,如果我使用self.buttonWidth,它在leftButton 中有效,但在rightButton 中无效。

【问题讨论】:

  • JRTopView.buttonWidth 不起作用,因为 buttonWidth 是实例属性而不是计算的类属性。尝试使用self.buttonWidth

标签: ios swift


【解决方案1】:

由于buttonWidth 是一个实例属性,因此访问它的唯一方法是通过JRTopView 的实例。

如果你不在这个班级,你可以创建一个新实例并执行yourInstance.buttonWidth,或者如果你在班级内部,则只需执行buttonWidth/self.buttonWidth

但是,作为一个常量,对于JRTopView 的所有实例而言,它始终具有相同的值,因此将其提升到类级别会更有意义:

static let buttonWidth:CGFloat = 150

这应该允许你做JRTopView.buttonWidth

【讨论】:

  • 如果我使用 self.buttonWidth 它在 leftButton 中有效,但在 int rightButton 中无效
  • leftButtonrightButton 代码块都只运行一次,两者的区别在于leftButton 中的lazy 关键字。使用lazy,您可以在内部引用self,因为该块只有在您在代码中引用它时才会运行(也就是在init 之后,一旦实例准备好)。然而,对于rightButton,由于它没有lazy 关键字,它会在JRTopView 的新实例创建后立即运行(将其视为急切初始化),这发生在init 之前运行,所以self 还没有准备好,不能被引用。
【解决方案2】:

这是在 Xcode 7.1 中构建的

class JRTopView: UIView {
    let buttonWidth:CGFloat = 150
    lazy var leftButton: UIButton! = {
        let btn = UIButton(type: UIButtonType.Custom)
        btn.backgroundColor = UIColor.greenColor()
        btn.frame = CGRectMake(-30, 30, self.buttonWidth, self.buttonWidth)
        return btn
    }()
    lazy var rightButton: UIButton! = {
        let btn = UIButton(type: UIButtonType.Custom)
        btn.backgroundColor = UIColor.greenColor()
        btn.frame = CGRectMake(-30, 30, self.buttonWidth, self.buttonWidth)
        return btn
    }()
}

【讨论】:

    猜你喜欢
    • 2015-06-27
    • 1970-01-01
    • 2018-05-02
    • 2014-11-16
    • 2019-03-20
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多