【发布时间】:2020-02-21 10:19:48
【问题描述】:
我有一个 collectionView 和一个包含我的类别的单元格。
我需要设置 Pressed 和 unpressed。两种状态。我的单元格只包含一个标签。没有按钮。这是我的一些代码。我认为这很容易做到。
class CategoryCollectionViewCell: UICollectionViewCell, NibLoadable {
enum state {
case pressed
case unpressed
}
@IBOutlet weak var label: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
Decorator.decorate(self)
addTargets()
}
func setText(text: String) {
label.text = text
}
func setFont(font: UIFont) {
label.font = font
}
func setFontColor(color: UIColor) {
label.textColor = color
}
func setColor(backgroundColor: UIColor, borderColor: CGColor, borderWidth: CGFloat) {
self.backgroundColor = backgroundColor
self.layer.borderColor = borderColor
self.layer.borderWidth = borderWidth
}
private func addTargets() {
let tap = UITapGestureRecognizer(target: self, action: #selector(tapped))
self.addGestureRecognizer(tap)
}
@objc func tapped() {
}
}
如您所见,我创建了更改单元格颜色的函数。
这是我在 VC 中的方法
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return categories.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let category = categories[indexPath.item]
if category.id == "userId" {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier:CategoryCollectionViewCell.name, for: indexPath) as! CategoryCollectionViewCell
cell.label.text = category.name
return cell
} else if category.id == "UniqueID" {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CategoryCollectionViewCell.name, for: indexPath) as! CategoryCollectionViewCell
let tap = UITapGestureRecognizer(target: self, action: #selector(addNewCategory))
cell.label.isUserInteractionEnabled = true
cell.label.text = "+ add"
cell.label.addGestureRecognizer(tap)
cell.setColor(backgroundColor: .white, borderColor: monPurple.cgColor, borderWidth: 1.0)
cell.setFontColor(color: .purple)
return cell
}
return UICollectionViewCell.init()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets (top: 10, left: 16, bottom: 10, right: 16)
}
朋友们有什么想法吗?
【问题讨论】:
标签: swift xcode collectionview