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