【发布时间】:2015-02-02 00:09:11
【问题描述】:
问题
我创建了一个带有自定义 UICollectionViewCell 的 UICollectionViewController。 自定义单元格包含一个大的矩形 UIView(名为 colorView)和一个 UILabel(名为 nameLabel)。
当集合首次填充其单元格并打印 colorView.frame 时,打印的帧具有不正确的值。我知道它们是不正确的,因为 colorView 框架比单元格框架本身大,即使 colorView 被正确绘制。
但是,如果我滚动 collectionView 足以触发对先前创建的单元格的重用,则 colorView.frame 现在具有正确的值! 我需要正确的框架,因为我想对 colorView 图层应用圆角,并且我需要正确的 coloView 大小才能做到这一点。 顺便说一句,如果您想知道,colorView.bounds 的大小值也与 colorView.frame 相同。
问题
为什么创建单元格时帧不正确?
现在是一些代码
这是我的 UICollectionViewCell:
class BugCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var colorView: UIView!
@IBOutlet weak var nameLabel: UILabel!
}
这是 UICollectionViewController:
import UIKit
let reuseIdentifier = "Cell"
let colors = [UIColor.redColor(), UIColor.blueColor(),
UIColor.greenColor(), UIColor.purpleColor()]
let labels = ["red", "blue", "green", "purple"]
class BugCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return colors.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as BugCollectionViewCell
println("ColorView frame: \(cell.colorView.frame) Cell frame: \(cell.frame)")
cell.colorView.backgroundColor = colors[indexPath.row]
cell.nameLabel.text = labels[indexPath.row]
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let width = self.collectionView?.frame.width
let height = self.collectionView?.frame.height
return CGSizeMake(width!, height!/2)
}
}
设置集合视图是为了一次垂直显示两个单元格,每个单元格都包含一个涂有颜色的大矩形和一个带有颜色名称的标签。
当我刚刚在模拟器上运行上述代码时,我得到以下打印结果:
ColorView frame: (0.0,0.0,320.0,568.0) Cell frame: (0.0,0.0,375.0,333.5)
ColorView frame: (0.0,0.0,320.0,568.0) Cell frame: (0.0,343.5,375.0,333.5)
这是一个奇怪的结果 - colorView.frame 的高度为 568 磅,而单元格框架只有 333.5 磅高。
如果我向下拖动 collectionView 并重复使用一个单元格,则会打印以下结果:
ColorView frame: (8.0,8.0,359.0,294.0) Cell frame: (0.0,1030.5,375.0,333.5)
ColorView frame: (8.0,8.0,359.0,294.0) Cell frame: (0.0,343.5,375.0,333.5)
在纠正colorView框架的过程中发生了一些我无法理解的事情。
我认为这与单元格是从 Nib 加载的事实有关,因此控制器不使用 init(frame: frame) 初始化程序,而是使用 init(coder: aCoder) 初始化程序,所以只要单元格已创建,它可能带有一些我无法编辑的默认框架。
如果能帮助我了解正在发生的事情,我将不胜感激!
我正在使用 Xcode 6.1.1。使用 iOS SDK 8.1。
【问题讨论】:
-
您如何定位 ColorView?您没有使用自动布局吗?我认为发生在您身上的是视图布局是从笔尖加载并转换为自动布局的。但是您的故事板视图控制器大小与模拟器不同。使用自动布局来定位您的视图,然后事情应该可以正常工作。
-
嘿@CharlieWu,我确实在使用自动布局... colorView 和 nameLabel 完全受限...
标签: ios xcode swift uicollectionview uicollectionviewcell