ios - 如何在 UICollectionViewCell 中选择按钮并快速检索另一个 Action 的状态?

标签 ios swift button uicollectionview cell

我在 uicollectioncell 中有两个按钮,我想选择一个按钮,然后根据第一个按钮的状态对另一个按钮执行操作。 我试过这个但它抛出:“快速 fatal error :在展开可选值时意外发现 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)

我该如何解决这个问题?

最佳答案

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

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

关于ios - 如何在 UICollectionViewCell 中选择按钮并快速检索另一个 Action 的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29214748/

相关文章:

ios - Xcode 强制 Swift 可选解包两次 (!!)

swift - 用按钮显示一些著名的名言和作者

ios - Touch ID 卡住 AVCaptureDevice

iphone - UILabel 更新在滚动期间停止 UIScrollView

iphone - 更改 iPhone 应用程序状态栏属性

ios - 图像不显示在 Firebase 的表格单元格中

ios - Google 翻译 api,来自此 ios 客户端应用程序的请求\u003cempty\u003e 被阻止

ios - 如何使 Swift 中的所有屏幕保持一致?

css - 如何在 Chrome 和 Firefox 中将按钮输入样式设置为相同?

qt - 如何在Qt中绘制一个 9-patch 按钮?