我試圖在界面生成器中配置自定義UIView
並獲取視圖進行渲染。每次我嘗試使用定製的Xib來做這件事時,我都可以在界面構建器中使xib看起來很好,但是當我試圖在界面生成器中將MyCustomView
放入UIVewController
時,出現各種編譯器錯誤。獲取@IBDesignable UIView繪製時不會崩潰界面生成器
每個教程中,我已經看了是這樣的:「就在你的類聲明的前面加上@IBDesignable
,把@IBInspectable
在瓦爾的前面,然後看魔術發生」(例如:WWDC 2015 video)。或者它在Objective-C中,或者它是一個帶有中文字幕的阿拉姆語的30分鐘視頻等。
我的最終目標是能夠拖放UIView,在身份檢查器中指定我的自定義類,並獲得xib填入我拖入的UIView並能夠調整@IBInspectable
屬性。
當我看着答案:
SO Post: @IBDesignable crashing agent
錯誤,我得到:
Base.lproj/Main.storyboard: error: IB Designables: Failed to render and update auto layout status for PlaylistViewController (o1G-QR-OwX): The agent crashed
Base.lproj/Main.storyboard: error: IB Designables: Failed to update auto layout status: The agent crashed
身份檢查我CurrentlyPlayingView
: 了我後,我的觀點
,我試圖去出現在上述底部的觀點故事板:
我的代碼:
import UIKit
@IBDesignable class CurrentlyPlayingView: UIView {
var view = UIView()
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!
@IBOutlet weak var progressSlider: UISlider!
// IBInspectable attributes
@IBInspectable public var titleLabelColor: UIColor = .black {
didSet {
self.titleLabel.textColor = titleLabelColor
}
}
@IBInspectable public var subtitleLabelColor: UIColor = .black {
didSet {
self.subtitleLabel.textColor = subtitleLabelColor
}
}
@IBInspectable public var sliderMinColor: UIColor = .blue {
didSet {
self.progressSlider.minimumTrackTintColor = sliderMinColor
}
}
@IBInspectable public var sliderMaxColor: UIColor = .red {
didSet {
self.progressSlider.maximumTrackTintColor = sliderMaxColor
}
}
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
initialConfig()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
initialConfig()
}
private func initialConfig() {
self.titleLabel.textColor = titleLabelColor
self.subtitleLabel.textColor = subtitleLabelColor
self.progressSlider.minimumTrackTintColor = sliderMinColor
self.progressSlider.maximumTrackTintColor = sliderMaxColor
}
// MARK: - Nib handlers
private func xibSetup() {
view = loadViewFromNib()
view.frame = bounds
// Make the view stretch with containing view
view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(view)
}
private func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "CurrentlyPlayingView", bundle: bundle)
// Assumes UIView is top level and only object in CustomView.xib file
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
return view
}
}
如果你已經做到了這一點,感謝您的閱讀。如果你看到我錯過了什麼,我歡迎你的建議。
我在你的實現中看不到'prepareForInterfaceBuilder'函數。 –