![](/img/trans.png)
[英]How to change the background color of a custom Collection View cell in swift iOS?
[英]Change custom cell content view color
我在主視圖控制器中添加了一個更改主題按鈕,其中有一個很小的表視圖。 我可以更改表格視圖單元格的“內容視圖”背景色以外的所有顏色,並且不能在cellForRowAt之外訪問它。
我該怎么辦? 無論如何,有沒有從我的自定義單元格觸發功能來更改顏色的功能?
您可以在控制器中添加屬性以確定單元格的顏色。 要更改顏色時,請調用tableView.reloadData()
。 這將使cellForRowAt
在每個可見的單元格上被調用,並且您可以在此委托方法中更改顏色。
Your viewController
YourViewController: UIViewController {
fileprivate var cellColor = UIColor.blue
// where you change color
func changeColor() {
cellColor = UIColor.red
// this will make the delegate method `cellForRowAt` be called on each visible row
tableView.reloadData()
}
}
cellForRowAt:
// delegate method
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuse id", for: indexPath) as! YourCustomCell
cell.contentView.backgroundColor = cellColor
// anything else...
return cell
}
如果您具有自定義單元格類並訪問委托方法以更改內容視圖的顏色,則可以通過實現delegate
來實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.