【发布时间】: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