【问题标题】:Set previously Cell Button image to its default state when another cell button is selected在选择另一个单元格按钮时将以前的单元格按钮图像设置为其默认状态
【发布时间】:2016-08-29 09:52:38
【问题描述】:

当另一个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
    }
}

谁能告诉我如何做到这一点? 谢谢

【问题讨论】:

  • 在更改按钮的选定状态之前,您是否尝试过self.collectionView.reloadData()
  • 是的,但它不能正常工作,当我按下单元格按钮时它会自动更改另一个按钮图像?
  • 很简单,您可以将索引值保存在 didselect 上,而不是重新加载并检查 cellForItemAtIndexPath 上的索引。
  • 对我不起作用,请检查我的代码吗?因为 didselect 方法只在单元格上起作用,而不是在单元格按钮上?
  • 感谢您帮助我(y)

标签: ios swift ios7 uicollectionview


【解决方案1】:
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
    }
 }

【讨论】:

  • 你能检查一下我的代码吗? drive.google.com/open?id=0B29ka7gbDAYxcWsySkdQY0FGZjQ 因为当我将代码更改为此代码时,我的项目在我的按钮类中显示错误
  • 谢谢,但是当我第一次按下按钮时它会播放并更改图像状态,但是当我点击另一个单元格按钮后它显示错误?无法将“UIView”(0x105ec9b20)类型的值转换为“UIButton”(0x105ed07e0)。在这一行让 bt:UIButton = self.view.viewWithTag(selectIndex) as! UIButton
  • 对不起,今天我在 viewDidLoad 上看到了你的消息;)。 // .........更新
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
  • 2021-02-08
  • 2020-03-05
  • 2021-11-05
相关资源
最近更新 更多