swift - XIB 无法从主包中加载。.... 为什么?
问题描述
场景:我正在尝试使用故事板的子视图引用 XIB 的“动态视图”。
但是我在加载位于主(当前)包中的特定 xib 文件时遇到问题。我认为这将是困难的。
以下是我的简单代码:
import UIKit
@IBDesignable
class AccountInformationView: UIView, Nib {
let nibName = "AccountInformationView"
var contentView: UIView?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
func commonInit() {
guard let view = loadViewFromNib() else { return }
view.frame = bounds
addSubview(view)
contentView = view
}
func loadViewFromNib() -> UIView? {
// let bundle = Bundle(for: type(of: self))
let mainBundle = Bundle.main
let nib = UINib(nibName: nibName, bundle: mainBundle)
// check the following line due to crash:
_ = nib.instantiate(withOwner: self, options: nil).first as? AccountInformationView
return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
}
它在该行崩溃:
nib.instantiate(withOwner: self, options: nil).first as? AccountInformationView
...原因:'无法在包中加载 NIB:'NSBundle(已加载)',名称为'AccountInformationView''
为什么我找不到 XIB?
解决方案
我看到您的项目中有一个名为 AccountInformationView的xib 。但这并不意味着您的bundle中有相应的nib。
首先,xib可能不在应用程序目标中,因此相应的nib永远不会进入构建的应用程序包。
其次,您没有提供足够的信息,但我猜测这段代码可能正在情节提要中运行(因为这是一个 IBDesignable 视图)——这永远不会起作用,因为当时没有捆绑包,甚至如果有的话,xib还没有变成nib。只有建筑才能制造笔尖。
推荐阅读
- python - 如何从 python 脚本运行具有多个参数的 perl 脚本
- python - 如何在一个 json 中解压缩三个不同的 json 以创建 3 个不同的 daatframes
- python - Pandas 按列表中的值分组(系列)
- django - Django - 使用聚合查询集获取数据时头疼
- phpstorm - 如何告诉 PhpStorm 函数参数是文件路径
- google-apps-script - 使用 Google 表格脚本创建散点图?
- regex - 用于将数字与单位和特殊符号(例如“120% g”等)匹配并对其进行特殊分组的正则表达式模式
- flutter - MissingPluginException(在通道 com.amazonaws.amplify/amplify 上找不到方法配置的实现)
- node.js - Promise All 中的 Node Js 循环不等待从 SOAP 获取请求
- javascript - 如何仅在滚动进入特定部分时设置间隔并立即清除?