【发布时间】:2019-04-06 17:53:51
【问题描述】:
我正在尝试制作自定义颜色选择器。左边的颜色是选择的颜色,其他颜色是其他选项。但是,当我 reloadData() 时,collectionView 边缘的一个单元格将在这个新单元格下方有一个先前的单元格。
我尝试制作自定义 collectionViewCell,然后将视图添加到默认 UICollectionViewCell。 我试图通过对视图应用阴影效果来诊断问题,这就是我知道单元格相互堆叠的方式。 以前我通过在情节提要中制作原型单元来对 collectionView 进行编码,但是对于我想要的功能,我无法做到这一点。
这是 cellForItemAtIndexPath 和重新加载集合视图时的代码。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = self.dequeueReusableCell(withReuseIdentifier: "colorCell", for: indexPath)
var color = UIColor.white
if colors.count == 0{
color = UIColor(red: CGFloat(mainManager.colors[indexPath.row][0] ), green: CGFloat(mainManager.colors[indexPath.row][1] ), blue: CGFloat(mainManager.colors[indexPath.row][2] ), alpha: 1.0)
}
else{
color = UIColor(red: CGFloat((colors[indexPath.row][0] ) ), green: CGFloat((colors[indexPath.row][1] ) ), blue: CGFloat((colors[indexPath.row][2] ) ), alpha: 1.0)
}
if indexPath.row == 0{
let cellView = UIView()
cell.addSubview(cellView)
cellView.translatesAutoresizingMaskIntoConstraints = false
cellView.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true
cellView.centerXAnchor.constraint(equalTo: cell.centerXAnchor).isActive = true
cellView.widthAnchor.constraint(equalTo: cell.widthAnchor, multiplier: 0.8).isActive = true
cellView.heightAnchor.constraint(equalTo: cell.heightAnchor, multiplier: 0.8).isActive = true
cellView.roundEdgesAndShadow()
cellView.backgroundColor = color
}
else{
let centerView = UIView()
cell.addSubview(centerView)
centerView.translatesAutoresizingMaskIntoConstraints = false
centerView.centerXAnchor.constraint(equalTo: cell.centerXAnchor).isActive = true
centerView.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true
centerView.widthAnchor.constraint(equalTo: cell.widthAnchor, multiplier: 0.4).isActive = true
centerView.heightAnchor.constraint(equalTo: cell.heightAnchor, multiplier: 0.4).isActive = true
centerView.roundEdgesAndShadow()
centerView.backgroundColor = color
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if colors.count == 0{
colors = mainManager.colors.sorted(by: { (a, b) -> Bool in
if a == mainManager.colors[indexPath.row]{
return true
}
else{
return false
}
})
}
else{
colors = mainManager.colors.sorted(by: { (a, b) -> Bool in
if a == self.colors[indexPath.row] {
return true
}
else{
return false
}
})
}
self.reloadData()
}
【问题讨论】:
-
永远不要在
cellForItem中添加视图,这实际上是使用collectionView时最糟糕的做法之一。改为子类UICollectionViewCell并在那里添加您需要的所有子视图。然后只dequeuecellForItem中的单元格并传递单元格可能需要的数据或模型。
标签: ios swift xcode uicollectionview uicollectionviewcell