myl*_*les 31 objective-c ios uicollectionview uicollectionviewcell swift
我有一个添加UICollectionView到我的,UIViewController并为它制作了一个自定义单元格.
我使用该sizeForItemAtIndexPath方法设置单元格的大小,并将每个单元格设置为UIScreen.mainScreen().bounds.width/2高度和宽度.基本上,每个单元格都是屏幕宽度的一半,高度相同.
然后我UIImageView在单元格内部,每个边缘固定到单元格的相对边缘,以便图像视图填充单元格.我也有一个UILabel在细胞中垂直和水平居中的.
但是,在第一次加载时,单元格的大小正确,但内容在左上角的小方块中要小得多.(如下图所示,我将单元格的contentView背景颜色设置为绿色,将imageView背景颜色设置为红色).
然后向下滚动一点(我假设一个可重复使用的单元格出列)所有单元格都很好(滚动后再保持正常).
是什么导致内容在首次加载时不能正确约束?
UPDATE
我的一些代码UIViewController:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("PrevDrawCell", forIndexPath: indexPath) as? PrevDrawCell
if cell == nil {
cell = PrevDrawCell()
}
cell!.drawVC = self
cell!.imageShortCode = self.tempImageURLs[indexPath.row]
// Pull image (async) and set after download
cell!.setupImage()
cell!.contentView.backgroundColor = UIColor.greenColor()
cell!.coverView.backgroundColor = UIColor.redColor()
cell!.dateLabel.font = UIFont(name: "HelveticaNeue-Light", size: 26)
cell!.dateLabel.text = "\(self.tempImageURLs.count-indexPath.row)/9"
return cell!
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let size = UIScreen.mainScreen().bounds.width/2
return CGSize(width: size, height: size)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsZero
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
Run Code Online (Sandbox Code Playgroud)
Dep*_*o B 60
它看起来仍然保留了contentView的100x100px基本大小,而单元格本身已经获得了正确的大小.您可以强制布局重置在返回单元格之前添加以下行:
cell?.layoutIfNeeded()
Run Code Online (Sandbox Code Playgroud)
小智 5
我曾经有过类似的问题(即使使用正确的自动布局,单元格的内容也不适合单元格)。该错误是由于未调用
super.layoutSubviews()Cell类中的重写函数layoutSubviews()引起的。