Swift,以编程方式更改UICollectionViewCell和UILabel(在单元格内)的宽度

man*_*sim 8 ios uicollectionview uicollectionviewcell uicollectionviewlayout swift

我已经将单元格的宽度(UICollectionViewCell)设置为等于UICollectionView的宽度,并且我试图使用包含在该单元格内的UILabel完全相同的事情.我认为下面的代码正好解释了我想要实现的目标.所以我在这里阅读了一些问题以及一些教程,但我仍然不确定如何实现这一目标.

在几个问题中它说的是使用collectionViewLayout但我真的在如何在我的代码中使用它.有任何想法吗?谢谢!

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("myCell", forIndexPath: indexPath) as LocationViewCell
    cell.locationLabel.text = "Hello there!"

    // Set cell & label width to 100%
    let collectionViewWidth = self.collectionView.bounds.size.width
    cell.frame.size.width = collectionViewWidth // Works
    cell.locationLabel.frame.size.width = collectionViewWidth // Does NOT 
Run Code Online (Sandbox Code Playgroud)

更新1

所以我添加了以下内容:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    // Set cell width to 100%
    let collectionViewWidth = self.collectionView.bounds.size.width
    return CGSize(width: collectionViewWidth, height: 35)
}
Run Code Online (Sandbox Code Playgroud)

发生的情况是,加载视图时,UILabel的宽度仍然很小.如果我转到另一个视图,然后返回,那么它是100%.所以我必须在viewDidLoad()右边做点什么?我已经在使用,self.collectionView.reloadData()但我猜这只是用于数据.

更新2

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("locationCell", forIndexPath: indexPath) as LocationViewCell
    cell.locationLabel.text = "Hello UILabel"

    // Set cell width to 100%
    let collectionViewWidth = self.collectionView.bounds.size.width
    cell.frame.size.width = collectionViewWidth
    cell.locationLabel.frame.size.width = collectionViewWidth

    return cell
}
Run Code Online (Sandbox Code Playgroud)

Abi*_*ern 19

它不起作用,因为在调用此方法时,集合视图已经知道单元格应该有多大,因为它已从流委托方法获取它:

optional func collectionView(_ collectionView: UICollectionView,
                  layout collectionViewLayout: UICollectionViewLayout,
             sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
Run Code Online (Sandbox Code Playgroud)

这是您应该设置单元格大小的位置.