我在 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/