选择另一个单元格按钮时,将先前的单元格按钮图像设置为其默认状态

时间:2016-05-04 05:58:22

标签: ios swift ios7 uicollectionview

我想在选择另一个Cell Button时将之前选择的Cell Button图片更改为默认状态。

默认状态sender.selected = false未选择按钮时

按下按钮后sender.selected = true

"

func collectionView(collectionView: UICollectionView,
                    cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(
                   reuseIdentifier, forIndexPath: indexPath) as! RadioCollectionViewCell

    cell.btnPlay.addTarget(self,
        action: Selector("audioControlButtonAction:"),
        forControlEvents: UIControlEvents.TouchUpInside)
    cell.btnPlay.tag = indexPath.row
    return cell
}        

func audioControlButtonAction(sender: UIButton) {

    if sender.selected == false {
        sender.selected = true 
    } else {
        sender.selected = false
    }
}

任何人都可以告诉我怎么做到这一点? 感谢

1 个答案:

答案 0 :(得分:4)

var selectIndex:Int = -1

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell 
{
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! RadioCollectionViewCell

    cell.btnPlay.addTarget(self, action: Selector("audioControlButtonAction:"), forControlEvents: UIControlEvents.TouchUpInside)
    cell.btnPlay.tag = indexPath.row+1

    return cell
}

func audioControlButtonAction(sender: UIButton) 
{
    if selectIndex != -1 && selectIndex != sender.tag
    {
        let bt:UIButton = self.view.viewWithTag(selectIndex) as! UIButton
        if bt.selected == true
        {
            bt.selected = false
        }
    }

    if sender.selected == false
    {
        sender.selected = true
        selectIndex = sender.tag
    }
    else
    {
        sender.selected = false
        selectIndex = -1
    }
 }