Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 如何在collectionViewLayout中获取CollectionViewCell?_Swift_Uicollectionview_Uicollectionviewlayout - Fatal编程技术网

Swift 如何在collectionViewLayout中获取CollectionViewCell?

Swift 如何在collectionViewLayout中获取CollectionViewCell?,swift,uicollectionview,uicollectionviewlayout,Swift,Uicollectionview,Uicollectionviewlayout,下面是我的代码 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell : UniversalNewChatUsersCell = collectionView.dequeueReusableCell(withReuseIdentifier: "UniversalNewChatU

下面是我的代码

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

        cell.lblUsername.text = self.arrSelectedUsersToChat.object(at: indexPath.row) as? String

        cell.layoutSubviews()
        return cell
    }
我想根据内容改变单元格宽度,为此我使用了下面的方法

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 150.0, height: 44.0)
    }
目前我通过静态宽度。
现在我想要的是,我想要访问collectionViewLayout方法中的单元格,这样我就可以得到单元格标签,并根据这个标签计算它的宽度。我该怎么做

您可以通过调用collectionview的cellForItem来获取cell。用sizeForItemAt方法编写代码

if let collectionViewCell = collectionView.cellForItem(at: indexPath) as? YourCollectionViewCell {
}

在collectionViewLayout方法中执行以下操作:

if let myCell = collectionView.cellForItem(at: indexPath) as? UniversalNewChatUsersCell             
    print(myCell)
}

您在该方法中具有indexPath。因此,您可以猜测该标签的大小。@Denny您可以使用indexPath.item获取特定单元格的文本吗?致命错误:在展开可选值时意外发现为零。请检查您的单元格重用标识符,并将标识符的当前名称写在集合视图数据源方法中,以确定您的名称单间牢房你可以发布更多的代码来理解吗?你正在使用as!强制转换单元格!。if let需要一个可选的。应该是这样的?这个代码永远不会打印myCell。它会转到always else语句