【问题标题】:Swift, Change width of UICollectionViewCell and UILabel(inside the cell) programmaticallySwift,以编程方式更改 UICollectionViewCell 和 UILabel(在单元格内)的宽度
【发布时间】:2014-12-28 15:49:00
【问题描述】:

我已将单元格 (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)
}

当视图被加载时,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
}

【问题讨论】:

  • 更新 1 帮助我看到我应该比较集合视图大小,而不是视图控制器大小。谢谢!

标签: ios swift uicollectionview uicollectionviewcell uicollectionviewlayout


【解决方案1】:

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

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

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

【讨论】:

  • 我根据您的建议更新了问题。它几乎可以工作,但第一次出现时它仍然很小。如果我去另一个视图然后返回,这是我想要的宽度。我怎样才能使它在开始时显示正确的宽度?
  • 如何调整单元格内标签的大小?
  • 我在问题中添加了确切的代码。所以基本上我正在使用cell.locationLabel.frame.size.width
  • 在该行放一个断点,看看出来的尺寸是多少。我想你会看到问题所在。
  • 已解决!因此,您建议的代码设置了 cell 的宽度。添加代码后我遇到的问题是我必须设置 UILabel 的 宽度。我通过从 MainStoryboard 添加约束来做到这一点(选择标签并从最近邻居的左右添加 0 间距)!我想我应该让其他人知道他们是怎么做到的!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-27
  • 1970-01-01
  • 1970-01-01
  • 2017-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多