繁体   English   中英

能够从Storyboard和ViewController加载xib

[英]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的节标题)。

  1. 使用swift文件中的IBOutlet创建一个xib文件,设计您的界面以及与UI元素的必要连接
  2. 在您的视图控制器类的viewDidLoad方法中(从情节提要中实例化的一种)

     // Name your xib and swift class as Header let headerNib = UINib(nibName: "Header", bundle: nil) self.tableView.registerNib(headerNib, forHeaderFooterViewReuseIdentifier: "header") 
  3. 实现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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM