【问题标题】:How to load custom UIView from xib using Swift 2?如何使用 Swift 2 从 xib 加载自定义 UIView?
【发布时间】:2015-12-07 19:49:42
【问题描述】:

任务是创建自定义 UIView,使用 Swift 从 .xib 文件加载 UI。我该怎么做?

我尝试使用代码做到这一点:

import UIKit

@IBDesignable class CustomView: UIView {

var view: UIView!

@IBOutlet weak var label: UILabel!

override init(frame: CGRect) {
    super.init(frame: frame)
    xibSetup()
}

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

func xibSetup() {
    view = loadViewFromNib()
    view.frame = bounds
    view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]

    addSubview(view)
}

func loadViewFromNib() -> UIView {
    let bundle = NSBundle(forClass: self.dynamicType)
    let nib = UINib(nibName: "CustomView", bundle: bundle)
    let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView

    return view
}

}

它运行了,但由于 EXC_BAD_ACCESS 崩溃并显示消息:

warning: could not load any Objective-C class information. This will significantly reduce the quality of type information available.

实际上,我需要将此处给出的代码http://qnoid.com/2013/03/20/How-to-implement-a-reusable-UIView.html 转换为 Swift 2.0,但我不知道该怎么做。

【问题讨论】:

    标签: ios swift xib


    【解决方案1】:

    试试

    let yourView = NSBundle.mainBundle().loadNibNamed("youViewNibName", owner: self, options: nil).first as! YourView
    

    在您的 ViewController 类中执行此操作,然后您可以使用 coder 在所需的 init 中访问视图,您应该调用 xibSetup()

    【讨论】:

    • 我需要创建在 Storyboard 中呈现的可设计视图。
    【解决方案2】:

    是否正确,您的类称为 CustomView 并且您正在加载 CustomView.xib,其中 xib 中视图的类是 CustomView强>?

    如果是这样,你可能不明白自己在做什么

    【讨论】:

    • 是的,它是正确的,但我看不出有什么问题。我用这个解决方案iphonedev.tv/blog/2014/12/15/…就是我说的。
    • 刚刚在github上查了一下,注意在它的CustomView.xib类中CustomView并不是任何视图的类
    • 否则出现上述情况,你就陷入了循环
    猜你喜欢
    • 2017-10-01
    • 2015-02-03
    • 2020-05-16
    • 1970-01-01
    • 2016-10-31
    • 2016-07-31
    • 2015-11-27
    • 2018-06-15
    • 1970-01-01
    相关资源
    最近更新 更多