【问题标题】:Two UICollectionViews and two UICollectionViewCells in one UIViewController一个 UIViewController 中有两个 UICollectionView 和两个 UICollectionViewCell
【发布时间】:2014-10-02 04:03:11
【问题描述】:

我的故事板上有两个UICollectionViews,每个都有自己的出口:

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

在每个集合视图中,我想使用不同类型的单元格。所以我创建了一个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
    }
}

我收到编译器错误

预期返回 UITableCellView 的函数中缺少返回。

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

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

【问题讨论】:

    标签: ios swift uicollectionview


    【解决方案1】:

    这是因为您的代码中的 if 条件不是“详尽无遗”的,即存在执行可能到达函数末尾并且无法返回单元格的情况。 (例如,您将来可能会引入额外的集合视图)

    这是一个最简单的解决方法:

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

    【讨论】:

    • 这不仅解决了我的问题,而且我也觉得自己受过教育。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多