Ios 如何在UICollectionViewCell中选择按钮并在swift中检索另一个操作的状态?
我在uicollectioncell中有两个按钮,希望选择一个按钮,然后根据第一个按钮的状态对另一个按钮执行操作。 我尝试过这个方法,但它抛出了:“swift致命错误:在展开可选值时意外发现nil” 我将cellForItemAtIndexPath中的按钮设置为:Ios 如何在UICollectionViewCell中选择按钮并在swift中检索另一个操作的状态?,ios,swift,button,uicollectionview,cell,Ios,Swift,Button,Uicollectionview,Cell,我在uicollectioncell中有两个按钮,希望选择一个按钮,然后根据第一个按钮的状态对另一个按钮执行操作。 我尝试过这个方法,但它抛出了:“swift致命错误:在展开可选值时意外发现nil” 我将cellForItemAtIndexPath中的按钮设置为: let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! CustomC
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
}
}
将此功能添加为两个按钮的操作。在哪一行发生错误?此处:cell.firstButton.selected=true我猜
firstButton
是一个IBOutlet
?如果手动实例化单元格,则不会加载nib。这意味着firstButton
将不会连接,它将为零。是的,我的firstButton是一个IBOutlet。我怎样才能不手动实例化单元格?感谢您对此感兴趣!如果我使用此选项,我得到:无法将“UIView”(0x38671380)类型的值强制转换为“My_App.CustomCell”(0x508e98)。那么您的按钮不是单元格的直接子项。我会更新我的答案。谢谢,这对我有帮助!
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
}
}