ios - 一个 UIViewController 中的两个 UICollectionView 和两个 UICollectionViewCell

标签 ios swift uicollectionview

我的 Storyboard上有两个 UICollectionView,每个都有自己的导出:

@IBOutlet weak var daysCollectionView: UICollectionView!
@IBOutlet weak var hoursCollectionView: UICollectionView!

在每个 Collection View 中,我想使用不同类型的单元格。所以我创建了一个 DayCell 类和一个 HourCell 类。

然后在 cellForItemAtIndexPath:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell 
{ 
    if collectionView == self.dayCollectionView 
    {
       let cell = collectionView.dequeueReusableCellWithReuseIdentifier("dayCell", forIndexPath: indexPath) as DayCell
       ...
       return cell
    } 
   else if collectionView == self.hourCollectionView 
   {
       let cell: HourCell = collectionView.dequeueReusableCellWithReuseIdentifier("hourCell", forIndexPath: indexPath) as HourCell
        ...
    return cell
    }
}

编译器出错

Missing return in a function expected to return UITableCellView".

我是不是完全遗漏了什么,或者 if 语句中的返回在这种情况下不起作用?

还是我的做法完全错了?这似乎是每个人都在暗示的答案。我只是无法让它工作。

最佳答案

这是因为您代码中的 if 条件不是“详尽无遗”的,即存在执行可以到达函数末尾但无法返回单元格的情况。 (比如你以后可能会引入一个额外的collection view)

这是一个最简单的修复:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    if collectionView == self.dayCollectionView {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("dayCell", forIndexPath: indexPath) as DayCell
        ...
       return cell
    } else { // do not do this check: if collectionView == self.hourCollectionView {
       let cell: HourCell = collectionView.dequeueReusableCellWithReuseIdentifier("hourCell", forIndexPath: indexPath) as HourCell
        ...
        return cell
    }
}

关于ios - 一个 UIViewController 中的两个 UICollectionView 和两个 UICollectionViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26154338/

相关文章:

ios - 未触发自定义 segue 的展开

swift - 在现代C++中的虚拟函数中可以使用模板参数吗?

ios - 第一次触摸后隐藏和取消隐藏 UIButtons

ios - 适用于 iOS 的 MobileVLCKit 无法构建(pod 和框架)

ios - OCMock 测试分配对象并调用方法

iphone - 当 objective-c 中出现推送通知时,如何在没有用户交互的情况下将 iphone 应用程序从后台带到前台?

ios - Xcode 11 SPM 身份验证失败,因为未提供凭据

ios - UICollectionViewCell 中的 UITableView

ios - 触摸单元格时 UICollectionView 崩溃

ios - 用于 Swift 的 NSNotFound