能够从Storyboard和ViewController加载xib

时间:2016-10-02 12:15:56

标签: ios swift storyboard

我尝试创建完美的解决方案,直接从代码和UIView创建自定义Storyboard子类。但是,我没有找到任何解决方案。

对于通过情节提要的IBDesignable解决方案,我按照此示例http://supereasyapps.com/blog/2014/12/15/create-an-ibdesignable-uiview-subclass-with-code-from-an-xib-file-in-xcode-6进行了完美操作。

但是,如果我尝试通过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

有没有人找到与我分享的解决方案,因为它们有两种可能性?

我需要它,因为我应该在故事板中使用此UIView,并将其作为UITableview SectionHeader

2 个答案:

答案 0 :(得分:1)

为了保留这两种情况,我更喜欢在我的子类声明中写这个:

@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

}

所以它有效;)

答案 1 :(得分:0)

以下是如何在从故事板中实例化的视图控制器中使用xib(在您的情况下作为UITableView的节头)。

  1. 使用swift文件中的IBOutlets创建一个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;
    }
    
  4. 这就是你需要做的一切。

相关问题