[英]How to load custom UIView from xib using Swift 2?
任務是創建自定義UIView,以使用Swift從.xib文件加載UI。 我怎么做?
我嘗試使用代碼來做到這一點:
import UIKit
@IBDesignable class CustomView: UIView {
var view: UIView!
@IBOutlet weak var label: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "CustomView", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
}
它運行,但是崩潰與EXC_BAD_ACCESS並顯示以下消息:
warning: could not load any Objective-C class information. This will significantly reduce the quality of type information available.
實際上,我需要將此處提供的代碼http://qnoid.com/2013/03/20/How-to-implement-a-reusable-UIView.html轉換為Swift 2.0,但是我不知道該怎么做。
嘗試
let yourView = NSBundle.mainBundle().loadNibNamed("youViewNibName", owner: self, options: nil).first as! YourView
在ViewController類中執行此操作,然后可以使用編碼器訪問必需的init中的視圖,在此應調用xibSetup()
。
是正確的,您的類稱為CustomView並且正在加載CustomView.xib ,而xib中視圖的類是CustomView嗎?
如果是這樣,您可能不了解自己在做什么
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.