如何在没有viewcontroller作为所有者的情况下将nib实例化为视图?

问题描述 投票:0回答:1

我有一个UICollectionViewCell的子类,我想单独测试它自己。如何在没有所有者的情况下自行实例化(是否可能?)?

swift uicollectionviewcell xctest
1个回答
1
投票

有可能的。在这段代码中,我假设您的单元类名称是:CustomCollectionViewCell,它位于CustomCollectionViewCell.xib文件中:

let bundle = Bundle(for:CustomCollectionViewCell.self)
let nib = UINib(nibName: "CustomCollectionViewCell", bundle: bundle)
//nibName should be the same as your file name
let cell = nib.instantiate(withOwner: nil, options: nil).first as? CustomCollectionViewCell
© www.soinside.com 2019 - 2024. All rights reserved.