2017-02-17 7 views
0

У меня есть UICollectionView, который использует пользовательские файлы xib для своих ячеек. В ячейке у меня установлен флажок ImageView. Я хочу изменить образ «ImageView1», когда он был записан на пленку. Я попробовал следующий фрагмент кода, но это не работает для меняИзменить изображение Посмотреть изображение на UICollectionViewCell по ссылке

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

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! V_Cell 

    if show_delete == true { 
     cell.img_delete.image = UIImage(named: "checked") 
    } 
} 

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! V_Cell 

    // Configure the cell 

    let data = valves_[indexPath.row] 
    cell.v_name.text = data 

    if show_delete == true { 
     cell.img_delete.isHidden = false 
    } else if show_delete == false { 
     cell.img_delete.isHidden = true 
    } 

    return cell 
} 

В этом коде я попытался изменить образ ImageView в didSelectItemAt.

My custom xib файл такой, как указано ниже.

enter image description here

Пожалуйста, предложите способ заставить его работать. Благодарю.

+0

Могу ли я узнать, пробовали ли вы мое решение? – KrishnaCA

+0

@ KrishnaCA Я решил небольшими корректировками к вашему предложению. Спасибо за лидерство. –

+0

Это почти похоже на мое решение. Но вместо того, чтобы иметь полный логический массив, вы используете массив int, чтобы уменьшить печать стопы памяти. Ницца – KrishnaCA

ответ

1

Для таких проблем всегда лучше хранить массив, который содержит элемент, заданный в заданном indexpath, или нет.

var checkArray: [Bool] = [Bool](repeating: false, count: numberOfRowsInCollectionView) 
// this should be the same size as number of items in collection view 

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

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! V_Cell 
    checkArray[indexPath.row] = !checkArray[indexPath.row] // if it's true, make it false and vice versa logic 
    collectionView.reloadItems(at: [indexPath]) 
} 

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

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! V_Cell 

    // Configure the cell 

    let data = valves_[indexPath.row] 
    cell.v_name.text = data 

    if show_delete == true { 
     cell.img_delete.isHidden = false 
    } else if show_delete == false { 
     cell.img_delete.isHidden = true 
    } 

    if checkArray[indexPath.row] { 
     cell.img_delete.image = //image for check 
    }else { 
     cell.img_delete.image = //image for no check 
    } 

    return cell 
} 
0

В заключение я решил использовать его по следующему коду.

var checkArray = [Int]() 

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
    if show_delete == true { 
     if checkArray.contains(indexPath.row) { 
      let index = checkArray.index(of: indexPath.row) 
      checkArray.remove(at: index!) 
      collectionView.reloadItems(at: [indexPath]) 
     } else { 
      checkArray.append(indexPath.row) 
      collectionView.reloadItems(at: [indexPath]) 
     } 
    } 
} 

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! V_Cell 

    // Configure the cell 
    let data = valves_[indexPath.row] 
    cell.v_name.text = data 

    if show_delete == true { 
     cell.img_delete.isHidden = false 
    } else if show_delete == false { 
     cell.img_delete.isHidden = true 
    } 

    if checkArray.contains(indexPath.row) { 
     cell.img_delete.image = UIImage(named: "checked_n") 
    } else { 
     cell.img_delete.image = UIImage(named: "unchecked") 
    } 

    return cell 
} 

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

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