Я целый день пытаюсь использовать CollectionViewController вместо ViewController. В моей раскадровке у меня есть CollectionViewController, коллекция внутри и кнопка внутри ячейки. Мой код: На CollectionViewController:Ошибка при попытке использовать CollectionViewController без ViewController
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