【问题标题】:How to select button in UICollectionViewCell and retrieve state for another action in swift?如何在 UICollectionViewCell 中选择按钮并快速检索另一个动作的状态?
【发布时间】:2015-05-26 17:00:23
【问题描述】:

我在 uicollectioncell 中有两个按钮,我想选择一个,然后根据第一个按钮的状态对另一个执行操作。 我试过这个,但它抛出:“快速致命错误:在展开可选值时意外发现 nil”

func firstAction(sender:UIButton) {
    var cell = Customcell()
    cell.firstButton.selected = true
    cell.firstButton.selected = !cell.firstButton.selected
}

@IBAction func secondAction(sender: UIBarButtonItem) {
    var cell = CustomCell()
    if cell.firstButton.selected == true {
        // DO stuff....
    } else {
        println("No button selected")
    }
}

我在 cellForItemAtIndexPath 中这样设置按钮:

let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! CustomCell
cell.firstButton.addTarget(self, action: "firstAction:", forControlEvents: UIControlEvents.TouchUpInside)
cell.secondButton.addTarget(self, action: "secondAction:", forControlEvents: UIControlEvents.TouchUpInside)

我该如何解决这个问题?

【问题讨论】:

  • 错误出现在哪一行?
  • 这里:cell.firstButton.selected = true
  • 我猜firstButtonIBOutlet?如果您手动实例化您的单元格,则不会加载笔尖。这意味着firstButton 不会被连接,它将为零。
  • 是的,我的 firstButton 是一个 IBOutlet。如何不手动实例化单元格?
  • 感谢您对此感兴趣!

标签: ios swift button uicollectionview cell


【解决方案1】:

在您的操作方法中,您创建 CustomCell 的新实例,而不是引用包含按钮的单元格。试试这个代码:

func buttonAction (sender: UIButton) {
    var cell = sender as UIView
    while (!cell.isKindOfClass(UITableViewCell)) {
        cell = cell.superview!
    }

    if sender == cell.firstButton {
        // Do something when the first button was touched
    } else if sender == cell.secondButton {
        // Do something when the second button was touched
    }
}

将此函数添加为两个按钮的操作。

【讨论】:

  • 如果我使用它,我会得到:无法将“UIView”(0x38671380)类型的值转换为“My_App.CustomCell”(0x508e98)。
  • 那么您的按钮不是单元格的直接子级。我会更新我的答案。
  • 谢谢,这对我有帮助!
猜你喜欢
  • 2020-09-21
  • 1970-01-01
  • 2011-08-15
  • 2020-05-29
  • 1970-01-01
  • 2020-01-21
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
相关资源
最近更新 更多