UICollectionView 在滚动出屏幕并重新打开时覆盖单元格标签
UICollectionView overwriting cell label when scrolled off screen and back on
我有一个带有 UICollectionView 的测试应用程序,当单元格第一次出现在屏幕上时,它会正确地绘制它的单元格,但会用新文本覆盖标签文本,当单元格滚动关闭并返回屏幕时,新文本会发生变化并以不同的方式放置.
以下是应用程序打开时的样子:
这是关闭和打开滚动后的样子:
这是使单元格出列并添加标签的代码:
func collectionViewTableLayoutManager(manager: DRCollectionViewTableLayoutManager!, collectionView: UICollectionView!, cellForRow row: UInt, column: UInt, indexPath: NSIndexPath!) -> UICollectionViewCell! {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(collectionViewCellIdentifier, forIndexPath: indexPath) as! UICollectionViewCell
cell.layer.borderColor = UIColor.blueColor().CGColor
cell.layer.borderWidth = 1
let subViews = cell.contentView.subviews
let labels = subViews.filter {[=10=] is UILabel } as! [UILabel]
let label: UILabel
if let lbl = labels.first {
label = lbl
} else {
label = UILabel(frame: cell.bounds)
label.font = UIFont.systemFontOfSize(10)
label.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth
label.textAlignment = NSTextAlignment.Center
label.backgroundColor = UIColor.clearColor()
cell.addSubview(label)
}
label.text = "\(indexPath.section):\(indexPath.row) / \(row):\(column)"
return cell
}
有什么想法吗?是 label.text 行和单元格的 IndexPath 以及行和列的值不同吗?我认为这些保持同步以使用正确的信息正确绘制单元格。 (这在 Obj C 中一切正常)
您直接将标签添加到单元格,但要检查标签是否存在于单元格的 contentView
中。尝试将标签添加到单元格的 contentView
,它应该可以工作。
通常,如果您知道所有这些单元格都需要该标签,您应该创建一个新单元格 class,其中已有自己的标签。这样,集合视图数据源就不必检查单元格内容并有条件地创建标签;标签已经存在,等待接受字符串。
我有一个带有 UICollectionView 的测试应用程序,当单元格第一次出现在屏幕上时,它会正确地绘制它的单元格,但会用新文本覆盖标签文本,当单元格滚动关闭并返回屏幕时,新文本会发生变化并以不同的方式放置.
以下是应用程序打开时的样子:
这是关闭和打开滚动后的样子:
这是使单元格出列并添加标签的代码:
func collectionViewTableLayoutManager(manager: DRCollectionViewTableLayoutManager!, collectionView: UICollectionView!, cellForRow row: UInt, column: UInt, indexPath: NSIndexPath!) -> UICollectionViewCell! {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(collectionViewCellIdentifier, forIndexPath: indexPath) as! UICollectionViewCell
cell.layer.borderColor = UIColor.blueColor().CGColor
cell.layer.borderWidth = 1
let subViews = cell.contentView.subviews
let labels = subViews.filter {[=10=] is UILabel } as! [UILabel]
let label: UILabel
if let lbl = labels.first {
label = lbl
} else {
label = UILabel(frame: cell.bounds)
label.font = UIFont.systemFontOfSize(10)
label.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth
label.textAlignment = NSTextAlignment.Center
label.backgroundColor = UIColor.clearColor()
cell.addSubview(label)
}
label.text = "\(indexPath.section):\(indexPath.row) / \(row):\(column)"
return cell
}
有什么想法吗?是 label.text 行和单元格的 IndexPath 以及行和列的值不同吗?我认为这些保持同步以使用正确的信息正确绘制单元格。 (这在 Obj C 中一切正常)
您直接将标签添加到单元格,但要检查标签是否存在于单元格的 contentView
中。尝试将标签添加到单元格的 contentView
,它应该可以工作。
通常,如果您知道所有这些单元格都需要该标签,您应该创建一个新单元格 class,其中已有自己的标签。这样,集合视图数据源就不必检查单元格内容并有条件地创建标签;标签已经存在,等待接受字符串。