我一整天都在尝试使用CollectionViewController而不是ViewController。在我的故事板中,我有一个CollectionViewController,内部的集合视图,以及单元格内的按钮。 我的代码是: 在CollectionViewController:尝试在没有ViewController的情况下使用CollectionViewController时出错
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfButtons
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CustomCollectionViewCell
cell.buttonInCell.selected = buttonsStatusList[indexPath.row]
cell.setContents(indexPath.row)
cell.updateButtonAppearance()
return cell
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let tappedCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CustomCollectionViewCell
tappedCell.buttonInCell.selected = !tappedCell.buttonInCell.selected
buttonsStatusList[indexPath.row] = tappedCell.buttonInCell.selected
tappedCell.updateButtonAppearance()
}
在CustomCollectionViewCell我:
@IBOutlet weak var buttonInCell: UIButton!
let buttonBorderWidth: CGFloat = 1.0
var buttonRadius: CGFloat!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
buttonRadius = frame.height/2
}
func setContents(row: Int) {
buttonInCell.setTitle(String(row + 1), forState: .Normal)
buttonInCell.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
buttonInCell.layer.cornerRadius = buttonRadius
buttonInCell.layer.borderColor = UIColor.blueColor().CGColor
buttonInCell.layer.borderWidth = buttonBorderWidth
}
func updateButtonAppearance() {
if buttonInCell.selected {
buttonInCell.setTitleColor(UIColor.whiteColor(), forState: .Normal)
buttonInCell.layer.backgroundColor = UIColor.blueColor().CGColor
} else {
buttonInCell.setTitleColor(UIColor.blueColor(), forState: .Normal)
buttonInCell.layer.backgroundColor = UIColor.whiteColor().CGColor
}
}
我想这个问题是在故事板的连接,但我不能找到它。 我得到的错误是: Could not cast value of type 'UICollectionViewCell' (0x10c7b6408) to 'UICollectionViewController.CustomCollectionViewCell' (0x10aee8470).
在dequeueReusableCellWithReuseIdentifier
您是否在故事板中设置了单元格的类名称? –
是的,@YiminLin,实际上,我也尝试删除有关CustomCell的所有内容,只使用一个UICollectionViewCell,但是我没有获取单元格的空白屏幕(我在故事板中将单元格的背景设置为蓝色) – Danowsky
是的@AaoIi。问题已经解决了!我仍然不知道为什么'didSelectItemAtIndexPath'不起作用,因此我可以取消选择按钮,但是您已经完成了自己的任务。非常感谢! – Danowsky