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

标签 ios swift uicollectionview uicollectionviewcell uicollectionviewlayout

我已将单元格 (UICollectionViewCell) 的宽度设置为等于 UICollectionView 的宽度,并且我正在尝试对包含在该单元格中的 UILabel 执行完全相同的操作。我认为下面的代码准确地解释了我想要实现的目标。所以我在 SO 中阅读了一些问题以及一些教程,但我仍然不确定如何实现这一目标。

在几个问题中,它是关于使用 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 

更新 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)
}

发生的情况是,加载 View 时,UILabel 的宽度仍然很小。如果我转到另一个 View 然后返回,则它是 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
}

最佳答案

它不起作用,因为在调用此方法时, Collection View 已经知道单元格应该有多大,因为它是从流委托(delegate)方法中获取的:

optional func collectionView(_ collectionView: UICollectionView,
                  layout collectionViewLayout: UICollectionViewLayout,
             sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize

这是您应该设置单元格大小的地方。

关于ios - Swift,以编程方式更改 UICollectionViewCell 和 UILabel(在单元格内)的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27677956/

相关文章:

ios - 需要在开发人员帐户中修改同一设备的UDID

ios - Ipad 上的背景图像不显示 100%

swift - CollectionView滚动交叉顶部uiview

ios - 隐藏导航栏 ios swift 生命周期方法未调用导致问题

ios - 安装 Xcode 9 后,Iphone 模拟器上的 Sprite kit 动画帧每秒少于 10。有什么办法可以解决这个问题

xcode - Swift - 检索 subview

ios - 如何在 Swift 中自动布局按钮

ios - UICollectionView 水平滚动照片库与 swift

ios - Objective-C UICollectionView 向上/向下滚动

ios - 如何将 UIView 放入 UICollectionView 中?