我有标签的集合视图,您可以选择标签。目前您可以选择任意多个,但我想将其限制为只有一个。只能选择一个标签。如果您选择一个标签并单击另一个标签,则之前的标签将返回到原始颜色,新选择的标签将更改颜色。
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: celltell = tc.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! celltell
cell.t.text = av[indexPath.item]
cell.t.layer.borderColor = UIColor.blackColor().CGColor
cell.t.backgroundColor = UIColor.whiteColor
cell.t.layer.borderWidth = 0.5
cell.t.tag = indexPath.row
let tapGesture = UITapGestureRecognizer(target: self, action: "tme:")
cell.t.addGestureRecognizer(tapGesture)
cell.t.userInteractionEnabled = true
return cell
}
func tme(gest: UITapGestureRecognizer){
let label: UILabel = gest.view as! UILabel
label.backgroundColor = UIColor.redColor
label.textColor = UIColor.whiteColor()
checker = label.tag
}
答案 0 :(得分:1)
take gloable variable at top of viewDidLoad
Var selectedIndex : Int
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: celltell = tc.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! celltell
cell.t.text = av[indexPath.item]
cell.t.layer.borderColor = UIColor.blackColor().CGColor
cell.t.backgroundColor = UIColor.whiteColor
cell.t.layer.borderWidth = 0.5
cell.t.tag = indexPath.row
if(indexPath.row == selectedIndex){
label.backgroundColor = UIColor.redColor
label.textColor = UIColor.whiteColor()
}
else{
label.backgroundColor = UIColor.whiteColor
label.textColor = UIColor.redColor()
}
let tapGesture = UITapGestureRecognizer(target: self, action: "tme:")
cell.t.addGestureRecognizer(tapGesture)
cell.t.userInteractionEnabled = true
return cell
}
func tme(gest: UITapGestureRecognizer){
let label: UILabel = gest.view as! UILabel
selectedIndex = label.tag
self.collectionView.reloadData();
}
答案 1 :(得分:0)
只需为标签设置突出显示的颜色。