ios - 如何在 swift iOS 中更改自定义 Collection View 单元格的背景颜色?
<p><pre><code> func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PlaceCollectionViewCell
//let imageView = UIImageView()
//cell.backgroundColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00)
cell.layer.borderWidth = 0.5
cell.layer.borderColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00).cgColor
//cell.placeLabel.tintColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00).cgColor
cell.layer.cornerRadius = 40
cell.layer.masksToBounds = true
print("places\(indexPath.row)")
//cell.placeLabel.text = places as! String
cell.placeLabel.text = places
cell.placeLabel.textColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PlaceCollectionViewCell
if (indexPath.row == 0){
cell.backgroundColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00)
}
}
</code></pre>
<p>我创建了一个自定义 <code>collectionViewCell</code>。当我单击其中一个单元格时,它的 <code>backgroundColor</code> 应该会改变。我怎样才能做到这一点?</p>
<p>我已经在 <code>didSelectItemItamAt indexpath</code> 方法中尝试过,但它不起作用。请帮忙。</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您可以使用 <a href="https://developer.apple.com/reference/uikit/uicollectionviewcell/1620138-selectedbackgroundview" rel="noreferrer noopener nofollow"><code>selectedBackgroundView</code></a> <code>UICollectionViewCell</code> 的属性,在 <code>cellForItemAt indexPath</code> 内设置该属性,现在当您选择单元格时,它将自动更改该单元格的 <code>backgroundColor</code>。</p>
<pre><code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PlaceCollectionViewCell
//Your other code
//Add code to set selectedBackgroundView property
let view = UIView(frame: cell.bounds)
// Set background color that you want
view.backgroundColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00)
cell.selectedBackgroundView = view
return cell
}
</code></pre>
<p>现在使用它不需要更改 <code>didSelectItemAt indexPath</code> 中单元格的 <code>backgroundColor</code> 它将自动工作并更改该选定单元格的 <code>backgroundColor</code> .</p></p>
<p style="font-size: 20px;">关于ios - 如何在 swift iOS 中更改自定义 Collection View 单元格的背景颜色?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/41157918/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/41157918/
</a>
</p>
页:
[1]