Sunday, July 19, 2026
HomeiOS Developmentios - Once I choose a cell from my collectionView to focus...

ios – Once I choose a cell from my collectionView to focus on it, a special cell from the entered indexPath will get highlighted as an alternative

[ad_1]

Here is my code:

extension ViewController: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection part: Int) -> Int {
        return itemArray.rely
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        var cell = UICollectionViewCell()
        
        if let itemCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath) as? UserItemCellCollectionViewCell {
            
            itemCell.config(itemArray[indexPath.row])
            
            cell = itemCell
        }
        cell.layoutIfNeeded()
        return cell
    }
}

extension ViewController: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        for merchandise in itemArray {
            merchandise.isSelected = false
        }
        
        itemArray[indexPath.row].isSelected = true
        highlightSelectedItem(place: indexPath)
        
        userItemView.reloadData()
    }
    
    func highlightSelectedItem(place: IndexPath) {
        
        for cell in userItemView.visibleCells {
            cell.layer.borderColor = UIColor.clear.cgColor
        }
        
        userItemView.cellForItem(at: place)?.layer.borderColor = UIColor.systemBlue.cgColor
        userItemView.cellForItem(at: place)?.layer.borderWidth = 2.0
        userItemView.cellForItem(at: place)?.layer.cornerRadius = 10
    }
}

You possibly can see right here that I’ve only a easy scrolling collectionView, and once I faucet on the pokeball for instance, then the cell for the elephant may have the whole lot from the highlightSelectedItem() operate utilized to it as an alternative of the one which I truly tapped on.

At one level I subtracted 1 from the indexPath.merchandise (and indexPath.row) and it appeared to work, however once I chosen the 0th merchandise (first merchandise on the left within the picture) it would not truly spotlight it as a result of it was technically within the place of itemArray[-1] so it did not exist.

Any concept as to what I can do to get it to focus on the border of the cell I choose?

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments