[英]@IBDesignable UIView not calling init within storyboard
我有一個@IBDesignable
的UIView
@IBDesignable
class MyView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
private func sharedInit(){
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = .blue
}
}
當我將這個UIView
放在 Storyboard 中,並將它的類分配給Identity inspector 中的MyView
時, UIView
仍然具有默認背景顏色。 為什么它的背景顏色不是故事板中的UIColor.blue
? 而且,我怎樣才能做到這一點,拜托?
謝謝你的幫助。
從故事板初始化此視圖的初始化程序將在運行時調用,為了在編譯時更新故事板中的視圖,您應該嘗試包含在編譯時更新故事板 xib 文件的prepareForInterfaceBuilder
。
我建議你在創建 @IBDesignable 類時做多件事:
@IBDesignable
標簽標記類@IBInspectable
標記UIView
屬性,然后您將能夠使用StoryBoard更改此屬性的值willSet
中設置配置代碼,該屬性在屬性取值之前是變化的觀察者,或在屬性didSet
后didSet
。prepareForInterfaceBuilder()
進行額外的設置,它覆蓋了它的超類UIView
簡單易行!
您的代碼應如下所示:
import UIKit
@IBDesignable
class myView: UIView {
@IBInspectable var storyBoardColor : UIColor = .red {
willSet(myVariableNameToCatch) {
self.backgroundColor = myVariableNameToCatch
}
}
fileprivate func sharedInit(){
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = storyBoardColor
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
sharedInit()
}
}
myView 的 storyBoardColor 的初始值為 red,您可以從 storyBoard 更改它;)
使用標簽@IBDesignable 創建視圖后。 接下來是使用@IBInspectable 設置您的屬性。
@IBDesignable
class MyView: UIView {
@IBInspectable var myBackgroundColour: UIColor? = nil {
willSet(v) {
self.backgroundColor = v
}
}
// YOUR EXISTING CODE HERE
}
現在,當您在Identity Inspector中將 MyView 設置為類名時。 您將能夠在Attributes Inspector 中看到您的可檢查屬性。 您可以在那里設置顏色,它會立即反映到您的自定義視圖中。
我認為使用自定義屬性設置背景顏色沒有任何用處,因為 UIView 具有設置背景顏色的默認屬性。
希望能幫助到你。
Swift 4.2 測試和工作。 這是最干凈的解決方案。
在 Xcode 中確保選中Editor -> Automatically refresh views
。
import UIKit
@IBDesignable
class BoxView: UIView {
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
layer.borderColor = borderColor?.cgColor
layer.borderWidth = borderWidth
layer.cornerRadius = cornerRadius
}
@IBInspectable var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.cgColor
setNeedsLayout()
}
}
@IBInspectable var borderWidth: CGFloat = 0.0 {
didSet {
layer.borderWidth = borderWidth
setNeedsLayout()
}
}
@IBInspectable var cornerRadius: CGFloat = 0.0 {
didSet {
layer.cornerRadius = cornerRadius
setNeedsLayout()
}
}
}
Identity Inspector
選擇Custom Class -> Class to "BoxView"
。Attributes Inspector
設置borderColor
、 borderWidth
和borderRadius
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.