【发布时间】:2018-08-29 23:19:07
【问题描述】:
我正在尝试以编程方式在 swift 类中添加 UICollectionView,没有任何情节提要,使用自定义单元格(每个单元格中都有一个简单的标签)
import Foundation
import UIKit
class BoardView : UIView, UICollectionViewDataSource, UICollectionViewDelegate {
var boardTable: UICollectionView!
var cellLabel:UILabel!
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
convenience init(frame: CGRect, title: String) {
self.init(frame: frame)
}
override init(frame: CGRect) {
super.init(frame: frame)
layout.sectionInset = UIEdgeInsets(top: 60, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 30, height: 30)
boardTable = UICollectionView(frame: self.frame, collectionViewLayout: layout)
boardTable.dataSource = self
boardTable.delegate = self
boardTable.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
boardTable.backgroundColor = UIColor.clear
self.addSubview(boardTable)
}
required init?(coder aDecoder: NSCoder) {
fatalError("MainViewis not NSCoding compliant")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath)
cellLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
cellLabel.textAlignment = .center
cellLabel.text = self.items[indexPath.item]
cell.contentView.addSubview(cellLabel)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
print("User tapped on item \(indexPath.row)")
}
}
我可以使用代码更改单元格背景
let cell = self.boardTable.cellForItem(at: IndexPath(row: 1 , section: 0))
cell?.backgroundColor = UIColor.lightGray
如何更改单元格文本颜色或单元格文本内容(cellLabel)?
提前感谢您的支持。
【问题讨论】:
-
如果您能够更改单元格背景颜色,请尝试访问您在单元格上添加的标签并更改其文本颜色,例如 cell?.cellLabel.textColor = UIColor.lightGray
-
如果我使用 cell?.cellLabel.textColor = UIColor.lightGray,我得到了那个错误:'UICollectionViewCell' 类型的值没有成员'cellLabel'
-
是的,cellLabel 不是 collectionViewCell 的成员,而是 BoardView 类的成员,理想情况下您应该能够使用 self 访问它。所以请尝试 self.cellLabel.textColor = UIColor.lightGray
-
它没有用。它仅在最后一个单元格文本处更改颜色
-
cell.contentView.addSubview(cellLabel)不要,根本不要。细胞被重复使用。使用自定义UICollectionViewCell和您可能访问的自己的初始化/属性。
标签: ios swift swift3 uicollectionview uicollectionviewcell