collectionView.cellForItem(at:indexPath)无法正常工作

时间:2017-03-05 07:54:15

标签: ios swift3 uicollectionview uicollectionviewlayout

我读过我的collectionViewController是UICollectionViewDelegateFlowLayout的委托, 我已正确注册我的手机,collectionView?.register(ActivityCell.self, forCellWithReuseIdentifier: cellId), 我已正确地取消了细胞并将其归还

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: ActivityCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! ActivityCell

        return cell
    }

但每当我尝试使用sizeForItemAtIndexPath函数中的indexPath检索单元格时,它都不会返回活动单元格

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if let cell: ActivityCell = self.collectionView?.cellForItem(at: indexPath) as? ActivityCell
        {
            let approximatewidthofcell = view.frame.size.width - 50
            let size = CGSize(width: approximatewidthofcell, height: 1000)
            let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 15)]

            let estimatedframe = NSString(string: cell.activitylabel.text!).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
            return CGSize(width: view.frame.size.width, height: estimatedframe.height)
        }
        else
         {
            return CGSize(width: view.frame.size.width, height: 200)
        }

    }

If块总是被忽略,而else块每次都被执行,我不知道接下来要操作什么代码,请帮忙

1 个答案:

答案 0 :(得分:1)

我没有看过集合视图一段时间,但我认为这是一个订单的事情,这个方法在cellForItem之前被调用。另外,你分配了数据源吗?