2015-09-27 3 views
0

Я целый день пытаюсь использовать 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

+0

Вы установили имя класса ячейки в раскадровке? –

+0

Да, @YiminLin, на самом деле, я также попытался удалить все о CustomCell и использовать только UICollectionViewCell, но я получаю пустой белый экран без ячеек (я установил фон ячейки синим в раскадровке) – Danowsky

+0

Да, @AaoIi. Проблема решена! Я до сих пор не знаю, почему 'didSelectItemAtIndexPath' не работает, поэтому я могу отменить выбор кнопок, но вы сделали свою часть. Большое спасибо! – Danowsky

ответ

-1

Ну Существовал много вопросов, которые были причиной этого произойти особенно, определив ваши вещи в CustomCell.

  • Я пересмотрел класс ячеек в cellForItemAtIndexPath.
  • Кнопка ручки в каждой ячейке щелкнула по addTarget методы updateButtonAppearance():

    cell.buttonInCell.addTarget(self, action: "updateButtonAppearance:", forControlEvents: UIControlEvents.TouchUpInside)

  • отслеживать выбранные элементы с buttonStatusList булева массивом внутри cellForItemAtIndexPath.

Update: Чтобы отменить выбор пункта и обратно цвет по умолчанию заменить, если заявление в updateButtonAppearance с:

if cell.buttonInCell.backgroundColor == UIColor.blueColor() { 
    cell.buttonInCell.setTitleColor(UIColor.blueColor(), forState: .Normal) 
    cell.buttonInCell.layer.backgroundColor = UIColor.whiteColor().CGColor 
    buttonsStatusList[sender.tag] = false 
} else { 
    cell.buttonInCell.setTitleColor(UIColor.whiteColor(), forState: .Normal) 
    cell.buttonInCell.layer.backgroundColor = UIColor.blueColor().CGColor 
    buttonsStatusList[sender.tag] = true 

} 

Примечание: Вам не нужно больше использовать didSelectItemAtIndexPath метод!

Смежные вопросы