Skip to main content
 首页 » 操作系统

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

2024年01月01日39bjzhanghao

我的 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 
    } 
}