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

#ios #iphone #swift

#iOS #iPhone #swift

Вопрос:

Я включил множественный выбор.И я добиваюсь успеха в изменении цвета ячейки при ее нажатии.Но я также хочу добавить изображение галочки в ячейку, когда оно выбрано, и удалить это изображение, когда я отменяю выбор ячейки.Я новичок в программировании Swift, пожалуйста, решите эту проблему. вот мой делегат представления коллекции и источник данных

 func collectionView(collectionView: UICollectionView,    numberOfItemsInSection section: Int) -> Int
{
 return marrCategoriesInfo.count
}

 func collectionView(collectionView: UICollectionView,   cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionVieww   .dequeueReusableCellWithReuseIdentifier("myCell", forIndexPath:    indexPath)as! CollectionViewCell
    for _ in 0 ..< marrCategoriesInfo.count  {
         cell.backgroundColor =   self.colorWithHexString(arrColors[indexPath.row])
         if (arrColors.count < marrCategoriesInfo.count)
         {
             arrColors.appendContentsOf(arrColors)
        }
    }



    cell.labellpersons.text = marrCategoriesInfo[indexPath.row] as?  String
    cell.labellpersons.textColor = UIColor .whiteColor()

       element = self.marrCategoriesInfo[indexPath.row] as! NSString
    if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad
    {
        stringSize = element.sizeWithAttributes([NSFontAttributeName:  UIFont.systemFontOfSize(25)]) as CGSize
        cell.labellpersons.sizeThatFits(stringSize)
        cell.layer.borderWidth = 2;
        cell.layer.borderColor = UIColor .blackColor().CGColor
        cell.layer.cornerRadius = 35;
        cell.labellpersons.textAlignment = .Center
    }
    else
    {
        stringSize = element.sizeWithAttributes([NSFontAttributeName:  UIFont.systemFontOfSize(12.0)]) as CGSize
        cell.labellpersons.sizeThatFits(stringSize)
        cell.layer.borderWidth = 1;
        cell.layer.borderColor = UIColor .blackColor().CGColor
        cell.layer.cornerRadius = 25;
        cell.labellpersons.textAlignment = .Center
    }     

     return cell
}


  func collectionView(collectionView: UICollectionView,  didSelectItemAtIndexPath indexPath: NSIndexPath)
{

   let acelll = collectionVieww.cellForItemAtIndexPath(indexPath)

  acelll?.backgroundColor = UIColor (red: 49/255, green: 30/255,   blue: 49/255, alpha:1.0)
  acelll?.layer.borderWidth = 2.0
    acelll?.layer.borderColor = UIColor .whiteColor() .CGColor


    IndexValue .addObject(indexPath.row)
    print("indexavalueis",IndexValue)

}

internal func collectionView(collectionView: UICollectionView,  didDeselectItemAtIndexPath indexPath: NSIndexPath)
{
  let acell = collectionView .cellForItemAtIndexPath(indexPath)
    acell?.backgroundColor =   self.colorWithHexString(arrColors[indexPath.row])
   acell!.layer.borderWidth = 1.0;
    acell!.layer.borderColor = UIColor .blackColor() .CGColor


   IndexValue.removeObject(indexPath.row)
        print(IndexValue)

}
  

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

1. Создайте один Nsmuwalbarray, содержащий NSMutalbeDictionaly. В NSMutalbeDictionaly вы добавляете один ручной ключ «isSelect». Теперь примените логику, когда вы щелкаете по выбранной ячейке, чем обновите NSMutalbeDictionaly ключ «IsSelected» на «true», иначе «false». С помощью этого ключа вы выбираете или отменяете выбор строки идентификатора

2. спасибо @ Wos, это полезно для меня