简体   繁体   English

加载链接到xib的自定义UIView的最佳方法

[英]Best way to load a custom UIView which is linked to a xib

I'm subclassing UIView (which will be a basic menu) and this custom view is linked to a xib file for its design. 我将UIView(将是一个基本菜单)子类化,并且此自定义视图链接到xib文件进行设计。

The files are : 这些文件是:

  • CustomView.swift CustomView.swift
  • CustomView.xib CustomView.xib

I'm working also with storyboard which has only one controller (the initial viewcontroller) which loads the CustomView this way (in its viewDidLoad method): 我也在使用只有一个控制器( 初始 viewcontroller)的故事板,这种控制器以这种方式(在其viewDidLoad方法中)加载CustomView:

self.menuView = CustomView(frame: self.view.bounds)
self.view.addSubview(self.menuView!)

I'm overriding the init method of the CustomView class as such : 我像这样重写CustomView类的init方法:

override init(frame: CGRect) {
    super.init(frame:frame)
    var view = UINib(nibName: "CustomView", bundle: nil).instantiateWithOwner(self, options: nil).lastObject() as CustomeView
    self.frame = frame
    view.frame = frame
    self.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
    view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
    self.addSubview(view)
}

This works well but the issue is that I have a CustomView inside another CustomView (with the self.addSubview(view) ) 这很好用,但是问题是我在另一个CustomView中有一个CustomView(带有self.addSubview(view)

Is there a better way to do that ? 有更好的方法吗?

Thanks a lot for any comment ! 非常感谢您的任何评论!

You can also do using: 您也可以使用:

self.menuView  =  NSBundle.mainBundle().loadNibNamed("CustomView", owner: self, options: nil)[0] as? CustomView
self.view.addSubview(menuView)

It is not a good approach. 这不是一个好方法。

do directly; 直接做

    self.menuView = UINib(nibName: "CustomView", bundle: nil).instantiateWithOwner(self, options: nil).lastObject() as CustomeView
    //set frame & mask of self.manuView if required
    self.view.addSubview(self.menuView!)

BTW there is no need to set frame and mask from code if using xib. 顺便说一句,如果使用xib,则无需从代码中设置帧和掩码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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