iOS swift: одиночная ячейка горизонтальной прокрутки UICollectionView не перезагружается

#ios #swift #uicollectionview #reloaddata

#iOS #swift #uicollectionview #reloaddata

Вопрос:

В моем приложении UICollection прокручивается горизонтально. была разработана ячейка для просмотра коллекции с двумя кнопками и одним UIView.

В каждую ячейку загружается две кнопки. когда пользователь нажимает одну кнопку, конкретная ячейка должна быть перезагружена, и UIView будет отображаться в этой ячейке, только другая ячейка не отображается.

Здесь я прикрепил изображение collectionview: введите описание изображения здесь

Вот мой код:

      @IBOutlet weak var dataCollectionView: UICollectionView!
        var addIndexArray:[Int] = []
        var arraySelectedFilterIndex = [IndexPath]()
        
        self.listArr = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t"]
        
        override func viewDidLoad() {
                super.viewDidLoad()
             self.dataCollectionView.reloadData()
        }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return (lvsnListArr.count/2)
        }
    
          func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
                
                let cell = dataCollectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier_CollectionView, for: indexPath as IndexPath) as! DataCell
        
                if self.arraySelectedFilterIndex.contains(indexPath) {
        
                    cell.buttonView.isHidden = false
        
                }else{
                   cell.buttonView.isHidden = true
                }
                
                cell.btn1.setTitle(lvsnListArr[2 * indexPath.row], for: .normal)
                cell.btn1.tag = indexPath.row
                cell.btn1.addTarget(self, action: #selector(btnPressed(sender:)), for: .touchUpInside)
        
                cell.btn2.setTitle(lvsnListArr[2 * indexPath.row   1], for: .normal)
                cell.btn2.tag = indexPath.row
                cell.btn2.addTarget(self, action: #selector(btn2Pressed(sender:)), for: .touchUpInside)
        
                return cell
            }
    
        @objc func btnPressed(sender: UIButton) {
            
            self.addIndexArray.append(sender.tag)
            
            let hitPoint = sender.convert(CGPoint.zero, to: dataCollectionView)
            if let indexPath = dataCollectionView.indexPathForItem(at: hitPoint) {
                print("indexPath--->",indexPath)
                self.arraySelectedFilterIndex.append(getIndexPath)
                self.dataCollectionView.reloadItems(at: [getIndexPath])
                
            }
        }

  @objc func btn2Pressed(sender: UIButton) {
    
    self.addIndexArray.append(sender.tag)
    
    let hitPoint = sender.convert(CGPoint.zero, to: dataCollectionView)
    if let indexPath = dataCollectionView.indexPathForItem(at: hitPoint) {
        print("indexPath--->",indexPath)
        self.arraySelectedFilterIndex.append(getIndexPath)
        self.dataCollectionView.reloadItems(at: [getIndexPath])
        
    }
}
 

Моя ошибка:

Я щелкнул ячейку btn1 одним действием BTN нажал на одну ячейку при загрузке и отобразил изображение следующей ячейки. оба изображения перекрываются в collectionview.

Здесь я прикрепил изображение своей проблемной ячейки.

введите описание изображения здесь

Здесь я получил cell indexpath и indexpath.row, как я могу проверить и исправить эту проблему в ячейке для строки. борюсь с этим моментом.

Kinldy поможет исправить эту проблему. Заранее спасибо.

Комментарии:

1. вы отлажены, что это позволяет HitPoint = sender.convert(CGPoint.zero, to: dataCollectionView) дает вашей ячейке правильный indexPath ??, Я думаю, какая-то проблема в Indexpath

2. да, отлажено для получения indexPath. как перезагрузить одну ячейку.. помогите мне

Ответ №1:

Вы можете перезагрузить отдельную ячейку, как вы делаете в действии кнопки

 self.dataCollectionView.reloadItems(at: [getIndexPath])
 

или

Вы можете получить ячейку в действии кнопки, как показано ниже

 if let cell = self.dataCollectionView.cellForItem(at: indexPath) as? DataCell
{
        //Here you can write your view hide show code
        if self.arraySelectedFilterIndex.contains(indexPath) 
        {
            cell.buttonView.isHidden = false
        }
        else
        {
            cell.buttonView.isHidden = true
        }
}
 

Комментарии:

1. проверьте это условие, есть такая же проблема.. помогите мне.