无法从主 UIViewController 访问嵌入式 UICollectionView

Posted

技术标签:

【中文标题】无法从主 UIViewController 访问嵌入式 UICollectionView【英文标题】:Embedded UICollectionView can't be accessed from main UIViewController 【发布时间】:2016-01-21 20:59:08 【问题描述】:

我在我的主视图中嵌入了一个 UICollection 视图,我正在尝试向它提供已经下载并放入数组的数据。但是,在与主 VC 不同的类上定义的 CollectionView 委托似乎没有运行。谁能指出我做错了什么?

let reuseIdentifier = "Cell"

class DiarioCollectionView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource 

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int 
    return 1


func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
    if defaults.boolForKey("gotPL") 
        print(defaults.arrayForKey("playlistTitles")!.count) //This is not being called..
        return defaults.arrayForKey("playlistTitles")!.count
    
    print("No Data") //This is also not being called..
    return 0


func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell 
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
    print(indexPath)
    print(indexPath.item)
    print(indexPath.row)
    if defaults.boolForKey("gotPL") 
        let thumbIV = cell.viewWithTag(1) as! UIImageView
        let playTitle = cell.viewWithTag(2) as! UILabel

        thumbIV.image = UIImage(data: defaults.arrayForKey("playlistThumbnails")![indexPath.row] as! NSData)
        playTitle.text = defaults.arrayForKey("playlistTitles")![indexPath.row] as? String
        return cell
    

    return cell

(UICollectionView 定义为 DiarioCollectionView 类的实例,在我的主 ViewController 中)

【问题讨论】:

【参考方案1】:

您在哪里加载数据? 集合视图的委托应该是您的主视图。 如果您所指的 mainView 是一个视图控制器,那么它应该同时实现 dataSource 和委托协议。

您还需要设置您的 collectionView 的委托(UICollectionViewDelegate 和 UICollectionViewDataSource 协议)

您可以在情节提要中或通过代码设置这两个委托:

self.YOURCOLLECTIONVIEW.dataSource = self
self.YOURCOLLECTIONVIEW.delegate = self

【讨论】:

BabyShung 是对的,您的视图控制器应该是委托,而不是集合视图本身。

以上是关于无法从主 UIViewController 访问嵌入式 UICollectionView的主要内容,如果未能解决你的问题,请参考以下文章

无法从 UIViewController 访问 UIView

从主窗体引用子窗体错误

从主应用程序目标 SwiftUI 访问 WidgetKit IntentTimelineProvider

从主类访问数组

从主访问类的受保护成员

如何从主应用程序访问组件中选择的项目