2015-12-07 52 views
0

我有很多按鈕相同size,我想從懶惰變量設置恆定的寬度,我應該怎麼做? JRTopView.buttonWidthbuttonWidth都不起作用。swift lazy var使用讓常數

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,但不rightButtonenter image description here

+0

'JRTopView.buttonWidth'不起作用,因爲buttonWidth是一個實例屬性,而不是計算的類屬性。嘗試使用'self.buttonWidth'。 – dasdom

回答

2

由於buttonWidth是一個實例屬性,訪問它的唯一方法是通過JRTopView的實例。

您可以創建一個新實例,如果您不在本課程中,則可以執行yourInstance.buttonWidth;如果您在此課程中,則只需執行buttonWidth/self.buttonWidth

然而,作爲一個常數,它始終擁有的JRTopView所有實例相同的值,它會更有意義,它提升爲一類等級:

static let buttonWidth:CGFloat = 150

這應該允許你這樣做JRTopView.buttonWidth

+0

如果我使用self.buttonWidth它在leftButton中工作,但不是int rightButton –

+0

'leftButton'和'rightButton'代碼塊只運行一次,兩者的區別在於'leftButton'中的'lazy'關鍵字。使用'lazy',你可以在裏面引用'self',因爲這個塊只有在代碼中引用時纔會運行(也就是說,在'init'後面,一旦實例準備就緒後)。然而,使用'rightButton',因爲它沒有'lazy'關鍵字,只要創建了一個'JRTopView'的新實例(認爲它是急切的初始化),就會在'init'之前發生運行,所以'self'沒有準備好,不能被引用。 – Edgar

+0

真的很棒,合理的提交。謝謝! –

1

這建立在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 
    }() 
}