[英]Load a ViewController code from a xib project imported to a storyboard project.
[英]Be able to load xib from both Storyboard and ViewController
我正在嘗試創建一個完美的解決方案,以直接從代碼和Storyboard
創建自定義UIView
子類。 但是,我沒有找到任何解決方案。
對於通過情節IBDesignable
解決方案,我遵循了以下示例http://supereasyapps.com/blog/2014/12/15/create-an-ibdesignable-uiview-subclass-with-code-from-an-xib-file-in -xcode-6並完美運行。
但是,如果我嘗試通過調用此Extension方法通過UIViewController
調用此子類:
extension UIView {
class func loadFromNibNamed(nibNamed: String, bundle : NSBundle? = nil) -> UIView? {
return UINib(
nibName: nibNamed,
bundle: bundle
).instantiateWithOwner(nil, options: nil)[0] as? UIView
}
}
它崩潰並表示錯過this class is not key value coding-compliant for the key
。
有人找到了可以與我共享的解決方案嗎?
我需要它,因為我應該在情節UITableview SectionHeader
將此UIView
用作UITableview SectionHeader
為了保留這兩種情況,我更喜歡在子類聲明中編寫以下代碼:
@IBDesignable class CustomView: UIView {
var view: UIView!
@IBOutlet weak var button: UIButton!
@IBOutlet weak var label: UILabel!
func xibSetup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "CustomView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
}
這樣,我可以看到它並將其添加到storyboard
。 在ViewForHeaderInSection
方法中,我這樣寫:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = UIView()
let view:CustomView = CustomView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 30))
view.label.text = "header title: \(section)"
header.addSubview(view)
return header
}
這樣就可以了;)
這是在情節提要中實例化的視圖控制器中使用xib的方法(在您的情況下為UITableView
的節標題)。
在您的視圖控制器類的viewDidLoad
方法中(從情節提要中實例化的一種)
// Name your xib and swift class as Header let headerNib = UINib(nibName: "Header", bundle: nil) self.tableView.registerNib(headerNib, forHeaderFooterViewReuseIdentifier: "header")
實現UITableViewDelegate
方法viewForHeaderInSection
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier("header") as! Header // Customise your header view here return header; }
這就是您需要做的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.