Подтвердить что ты не робот

Как получить ячейку atIndex в UICollectionView с быстрым?

Я делаю Collection view программным. Вот код в viewDidLoad func

let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
    layout.itemSize = CGSize(width: 90, height: 120)
    collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    collectionView!.dataSource = self
    collectionView!.delegate = self
    collectionView!.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
    collectionView!.layer.cornerRadius = 2
    collectionView!.backgroundColor = UIColor.redColor()
    self.containerView.addSubview(collectionView!)

И это мои функции просмотра коллекции

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 8
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
    cell.backgroundColor = UIColor.blackColor()
    cell.buttonView.addTarget(self, action: Selector("Action\(indexPath.row):"), forControlEvents: UIControlEvents.TouchUpInside)
    return cell
}

Идея: у меня есть кнопка в ячейке, и когда я нажимаю ее, ячейка должна менять цвет, вот функция действия

func Action0(sender: UIButton!) {
    var indexPath = NSIndexPath(forRow: 0, inSection: 0)
    let cell = collectionView!.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath ) as! CollectionViewCell
    cell.backgroundColor = UIColor.blueColor()

и это класс collectionViewCell,

class CollectionViewCell: UICollectionViewCell {

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

var buttonView: UIButton!
override init(frame: CGRect) {
    super.init(frame: frame)

    buttonView = UIButton.buttonWithType(UIButtonType.System) as! UIButton
    buttonView.frame = CGRect(x: 0, y: 16, width: frame.size.width, height: frame.size.height*2/3)

    contentView.addSubview(buttonView)
}

}

Кнопка и действие работают, но ячейка не меняет цвет, я думаю, проблема в этой строке

let cell = collectionView!.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath ) as! CollectionViewCell
4b9b3361

Ответ 1

Это способ получить ячейку в заданном indexPath:

let cell = collectionView!.cellForItemAtIndexPath(indexPath)

Однако вы также можете попробовать:

cell.contentView.backgroundColor = UIColor.blueColor()

ПРИМЕЧАНИЕ.

Хотя вышеупомянутое, возможно, сработало, я хочу призвать вас попробовать другую реализацию для достижения той же функциональности. Ваша реализация потребует от вас отдельной функции Action # для каждого CollectionViewCell, а также для создания indexPath вручную в каждом из этих методов, когда у вас может быть только один!

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
    cell.backgroundColor = UIColor.blackColor()
    cell.buttonView.addTarget(self, action: Selector("action"), forControlEvents: UIControlEvents.TouchUpInside)
    return cell
}

и функция для этого метода будет выглядеть примерно так:

func action(sender: UIButton!) {
    var point : CGPoint = sender.convertPoint(CGPointZero, toView:collectionView)
    var indexPath = collectionView!.indexPathForItemAtPoint(point)
    let cell = collectionView!.cellForItemAtIndexPath(indexPath)
    cell.backgroundColor = UIColor.blueColor()
}

Просто предложение! Счастливое кодирование!:)

Ответ 2

попробуйте cell.selected, а затем измените цвет

Ответ 3

В Swift 2 вы можете получить строку с помощью:

let point : CGPoint = sender.convertPoint(CGPointZero, toView:myTableView)
let indexPath = myTableView.indexPathForRowAtPoint(point)
let cell = myTableView.cellForRowAtIndexPath(indexPath!)