首页 文章

从xib文件动态加载iOS视图

提问于
浏览
0

我一直在寻找一个关于如何在我的故事板中重用xib文件中的视图的简单示例,但是我发现它已经过时或者没有解决我的问题,情况就是我很简单:

  • 我的故事板中有一个viewController

  • 我从图书馆拖了两个视图

  • 我创建了一个myCustomView.xib和myCustomView.swift文件(它们现在是空的)

  • 我在viewController上有一个按钮(因此树(两个视图和一个按钮)在故事板中的viewController上一起设置)

  • 问题是:我希望在应用启动时动态加载一个视图,在按钮点击时加载另一个视图

  • 另一个问题:如何将myCustomView连接到该viewController

谢谢

2 回答

  • 1

    我已经实现了UIView的扩展:

    extension UIView {
    
        static func createInstance<T: UIView>(ofType type: T.Type) -> T {
            let className = NSStringFromClass(type).components(separatedBy: ".").last
            return Bundle.main.loadNibNamed(className!, owner: self, options: nil)![0] as! T
        }
    
    }
    

    这样,只要您以这种方式加载自定义视图,

    func override viewDidLoad() {
        super.viewDidLoad()
        let customView = UIView.createInstance(ofType: CustomView.self) 
        self.view.addSubview(customView)
    }
    
  • 3

    在自定义视图类中添加波纹管代码

    class MyCustomView: UIView {
    
    
       @IBOutlet var contentView: UIView! // take view outlet
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            xibSetup()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            xibSetup()
        }
    
    
        func xibSetup() {
            contentView = loadViewFromNib()
    
            // use bounds not frame or it'll be offset
            contentView!.frame = bounds
    
            //Make the view stretch with containing view
            contentView!.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
    
            // Adding custom subview on top of our view (over any custom drawing > see note below)
            addSubview(contentView!)
            layoutIfNeeded()
        }
    
        override func layoutIfNeeded() {
            super.layoutIfNeeded()
            print("layoutIfNeeded")
    
    
        }
    
        func loadViewFromNib() -> UIView! {
            let bundle = Bundle(for: type(of: self))
            let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
            let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
            return view
        }
    }
    

    在storyboard中将此类添加为超类视图 .

相关问题