【问题标题】:Swift: How to Reuse Custom View Loaded from NibSwift:如何重用从 Nib 加载的自定义视图
【发布时间】:2021-03-07 09:51:45
【问题描述】:

我的应用中有一个自定义单元格,我想在其他地方重复使用它。但是,它不会在UITableView 中,而是在UIScrollView 的内容视图中。考虑到可以以这种方式使用它,我面临的挑战是如何从 Nib 加载一次并多次重用此单元格。我试过了:

var myReusableCell = Bundle.main.loadNibNamed("SearchViewCell", owner: self, options: nil)?[0] as! SearchViewCell

当我循环遍历数据数组以创建 myReusableCell 的实例时,这显然会减慢我的应用程序的速度。我正在寻找在循环中重用这个 Nib 的方法。

for (index, dataObject) in self.dataObjects {
   var myReusableCell = Bundle.main.loadNibNamed("SearchViewCell", owner: self, options: nil)?[0] as! SearchViewCell //slow!
}

我试图将它加载到for 循环之外并复制单元格以重复使用它:

NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) 

但不成功。请告知是否可行。

【问题讨论】:

    标签: ios swift uitableview storyboard nib


    【解决方案1】:

    首先我需要说它听起来像是一个 UITableView 或 UICollectionView 用例。 话虽如此,我不确定,但您可以尝试深拷贝

    var myReusableCell = Bundle.main.loadNibNamed("SearchViewCell", owner: self, options: nil)?[0] as! SearchViewCell
        for (index, dataObject) in self.dataObjects {
            if let cell = myReusableCell.copy() as? SearchViewCell {
                // TODO update your dataObject values
            }
        }
    

    【讨论】:

    • 谢谢。使用 copy() 使我的应用程序崩溃并出现错误 SearchViewCell copyWithZone:]: unrecognized selector sent to instance
    • 嗨@Vad你可以提供一个copyWithZone函数的实现,并且在你的SearchViewcell中也符合NSCopying协议来解释如何复制你的数据。更多信息在这里robnapier.net/implementing-nscopying
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    相关资源
    最近更新 更多