2016-10-18 49 views
0

我跟隨tutorial在這裏創建一個可檢查和可設計的視圖。我只是想將邊框顏色,邊框寬度和圓角邊框功能添加到UIView中。爲什麼標記@IBInspectable的屬性不起作用?

我已成功顯示屬性。但是,無論我在故事板上設置了什麼,結果仍然像是如果他們不在那裏。沒有邊框,儘管我已將邊框設置爲寬度2和黑色。它不會在故事板和運行時顯示。我將邊框設置爲2寬度,但在運行時,我在didViewLoad上打印邊框寬度值,結果爲0.可能有什麼錯誤?

@IBDesignable extension view: UIView { 

    @IBInspectable var cornerRadius: CGFloat { 
     get { 
      return layer.cornerRadius 
     } 
     set { 
      layer.cornerRadius = newValue 
      layer.masksToBounds = newValue > 0 
     } 
    } 

    @IBInspectable var borderWidth: CGFloat { 
     get { 
      return layer.borderWidth; 
     } 
     set { 
      layer.borderWidth = borderWidth; 
     } 
    } 

    @IBInspectable var borderColor: UIColor? { 
     get { 
      return UIColor(CGColor: layer.borderColor!); 
     } 
     set { 
      layer.borderColor = borderColor?.CGColor 
     } 
    } 

} 

這不工作之一:

@IBDesignable class BOView: UIView { 

    @IBInspectable var cornerRadius: CGFloat { 
     get { 
      return layer.cornerRadius 
     } 
     set { 
      layer.cornerRadius = newValue 
      layer.masksToBounds = newValue > 0 
     } 
    } 

    @IBInspectable var borderWidth: CGFloat { 
     get { 
      return layer.borderWidth; 
     } 
     set { 
      layer.borderWidth = borderWidth; 
     } 
    } 

    @IBInspectable var borderColor: UIColor? { 
     get { 
      return UIColor(CGColor: layer.borderColor!); 
     } 
     set { 
      layer.borderColor = borderColor?.CGColor 
     } 
    } 

} 
+0

有你在IB打開菜單'Editor'➜'自動刷新Views'? – holex

+0

@holex該選項已打開。 –

+0

請參閱本教程:https://iosdevcenters.blogspot.com/2017/07/how-to-use-ibinspectable-in-swift-30.html –

回答

4

嘗試使用NEWVALUE而不是真正的價值。

例如,

@IBInspectable var borderWidth: CGFloat { 
    get { 
     return layer.borderWidth 
    } 
    set { 
     layer.borderWidth = newValue 
    } 
} 

陳,我更喜歡你正在做的方式,還要注意你正在嘗試做的是能夠從故事板上,無需使用IBDesignable。您可以在用戶定義的運行屬性中設置圖層屬性。

enter image description here

+0

在發佈之前是否檢查過此答案?它工作嗎? – holex

+0

@holex是的,我做了,它的工作 –

+0

Ooooooooh就是這樣!是的,我需要使用'newValue'而不是變量名。謝謝!!!!但IBDesignable仍然無法正常工作,但這是一個巨大的飛躍! –

相關問題