Retrieve position within a CollectionView

0

I am developing in IOS and I am a first-timer.

The idea is that when I started the program I made a collection View of buttons in the following way:

@IBOutlet weak var collectionView: UICollectionView!

    let taille = 45
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let identifier = "item"
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! CollectionViewCell
        cell.btnCollection.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
        return cell
    }

    @objc func buttonAction(sender: UIButton!) {
        sender.backgroundColor = UIColor.red
        sender.description =
    }

So far I only paint the button that I click on, what I want to know is whether there is the possibility of recovering the position within the button collection that I click

If it exists, what function to use?

    
asked by Ernesto Emmanuel Yah Lopez 30.01.2018 в 16:24
source

2 answers

1

If I understood what you want to achieve, the fastest way (although I do not like it that much) could be:

In the function of dataSource

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell

... add

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let identifier = "item"
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! CollectionViewCell
    cell.btnCollection.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    // agregando como 'tag' el indice del 'row'...
    cell.btnCollection.tag = indexPath.row
    return cell
}

... so that later:

@objc func buttonAction(sender: UIButton!) {
    let index = sender.tag // obtienes el indice del 'tag' ...
    sender.backgroundColor = UIColor.red
    sender.description =
}
    
answered by 22.02.2018 в 20:47
0

I think you're complicating yourself too much. You can treat the cell itself as a button. You have a function of the UICollectionViewDelegate that is

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
print(indexPath)
}

If you touch a cell, this method is executed and you know what cell is because the indexPath.row

indicates it to you     
answered by 28.02.2018 в 15:52