如何在 UICollectionViewCell 中使用 select 按钮并在 swift 中检索另一个操作的状态?

How to select button in UICollectionViewCell and retrieve state for another action in swift?

我在 uicollectioncell 中有两个按钮,我想 select 一个,然后根据第一个按钮的状态对另一个执行操作。 我试过这个但是它抛出了:"swift fatal error: unexpectedly found nil while unwrapping an Optional value"

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)

我该如何解决这个问题?

在您的操作方法中,您创建了 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
    }
}

将此功能添加为两个按钮的操作。