【问题标题】:Best way to load a custom UIView which is linked to a xib加载链接到 xib 的自定义 UIView 的最佳方法
【发布时间】:2014-10-25 17:15:34
【问题描述】:

我正在继承 UIView(这将是一个基本菜单),并且这个自定义视图链接到一个 xib 文件 它的设计。

文件是:

  • CustomView.swift
  • CustomView.xib

我也在使用故事板,它只有一个控制器(initial viewcontroller),它以这种方式加载 CustomView(在其 viewDidLoad 方法中):

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

我正在重写 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)
}

这很好用,但问题是我在另一个 CustomView 中有一个 CustomView(使用 self.addSubview(view)

有没有更好的方法来做到这一点?

非常感谢您的任何评论!

【问题讨论】:

  • 您能提供更多信息吗?所以你有两个 xib 文件并将一个 xib 的视图加载到另一个 xib 的视图中?首先,您有两个单独的 xib 文件的原因是什么?这很常见,但应该知道原因以提供良好的建议。
  • 所以我只有 1 个 xib 和一个附加到 xib 的自定义 UIView(通过 CustomClass),我在这个故事板中有一个故事板和一个视图控制器。我在初始视图控制器(方法 viewDidLoad)中以编程方式加载自定义视图

标签: ios objective-c uiview swift xib


【解决方案1】:

你也可以使用:

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

【讨论】:

    【解决方案2】:

    这不是一个好方法。

    直接做;

        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!)
    

    顺便说一句,如果使用 xib,则无需从代码中设置框架和掩码。

    【讨论】:

    • 这意味着所有者现在将是 viewController 而不是 UIView 的子类? “自制”组件不能像任何其他组件(UIButton,...)一样被实例化,这似乎真的很奇怪......
    猜你喜欢
    • 1970-01-01
    • 2015-02-03
    • 2020-05-16
    • 2017-10-01
    • 2016-07-31
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    相关资源
    最近更新 更多