从故事板中的外部xib文件加载视图

从故事板中的外部xib文件加载视图

本文介绍了从故事板中的外部xib文件加载视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在故事板中的多个viewcontrollers中使用视图。因此,我考虑在外部xib中设计视图,以便在每个viewcontroller中反映更改。但是如何从故事板中的外部xib加载视图呢?它甚至可能吗?如果不是这样的话,还有哪些其他选择可以适应这种情况呢?

解决方案

我的完整例子是
代码



将以下代码添加到.swift文件中,并连接.xib文件中的出口和操作。

  import UIKit 
class ResuableCustomView:UIView {

let nibName =ReusableCustomView
var contentView:UIView?

@IBOutlet弱var标签:UILabel!
@IBAction func buttonTap(_ sender:UIButton){
label.text =Hi
}

必需init?(编码器aDecoder:NSCoder){
super.init(coder:aDecoder)

guard let view = loadViewFromNib()else {return}
view.frame = self.bounds
self.addSubview(view )
contentView = view
}

func loadViewFromNib() - > UIView的? {
let bundle = Bundle(for:type(of:self))
let nib = UINib(nibName:nibName,bundle:bundle)
return nib.instantiate(withOwner:self,options :零)。首先是? UIView
}
}

使用



在故事板中的任意位置使用自定义视图。只需添加 UIView 并将类名设置为您的自定义类名。




I want to use a view throughout multiple viewcontrollers in a storyboard. Thus, I thought about designing the view in an external xib so changes are reflected in every viewcontroller. But how can one load a view from a external xib in a storyboard and is it even possible? If thats not the case, what other alternatives are availble to suit the situation abouve?

解决方案

My full example is here, but I will provide a summary below.

Layout

Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).

Make the swift file the xib file's owner.

Code

Add the following code to the .swift file and hook up the outlets and actions from the .xib file.

import UIKit
class ResuableCustomView: UIView {

    let nibName = "ReusableCustomView"
    var contentView: UIView?

    @IBOutlet weak var label: UILabel!
    @IBAction func buttonTap(_ sender: UIButton) {
        label.text = "Hi"
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        guard let view = loadViewFromNib() else { return }
        view.frame = self.bounds
        self.addSubview(view)
        contentView = view
    }

    func loadViewFromNib() -> UIView? {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName, bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as? UIView
    }
}

Use it

Use your custom view anywhere in your storyboard. Just add a UIView and set the class name to your custom class name.

这篇关于从故事板中的外部xib文件加载视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 14:51