I am a beginner to iOS development.
I do not know what is wrong with my code. I tried to set the default cell to index 0 when no cell is selected, but the checkmark does not appear. I would appreciate it if someone could give me a hint to solve this.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
switch collectionView.tag
{
case 1:
guard lastSelectedIndexPath != indexPath else { return }
if let index = lastSelectedIndexPath,
let lastSelectedCell = collectionView.cellForItem(at: index) as? CollectionViewCell1
{
lastSelectedCell.isSelected = false
}
case 2:
guard lastSelectedIndexPath != indexPath else { return }
if let selectedCell = collectionView.cellForItem(at: indexPath) as? CollectionViewCell1
{
selectedCell.isSelected = true
lastSelectedIndexPath = indexPath
if let selectedImage = selectedCell.imagesView.image {
selectedPersonImage.image = selectedImage
profileImage.image = selectedImage
selectedCharacterImage = selectedImage
personModels[0].icon = selectedImage
selectedCharacterImage = personModels[0].icon
selectedImageName = getImageName(for: selectedImage)
// Save the selection to UserDefaults
userDefaults.set(["section": indexPath.section, "item": indexPath.row], forKey: "selectedPersonIndex")
}
}
else
{
// Handle the case where cell is nil
print("Cell is nil for indexPath: (indexPath)")
}
case 3:
// Handle selection for collectionView with tag 3
guard lastSelectedIndexPath != indexPath else { return }
if let selectedCell = collectionView.cellForItem(at: indexPath) as? CollectionViewCell1 {
selectedCell.isSelected = true
lastSelectedIndexPath = indexPath
// Update the images and models based on the selected image
if let selectedImage = selectedCell.plantImg.image {
plantProfileImage.image = selectedImage
selectedPlantImage.image = selectedImage
selectedCharacterImage = selectedImage
plantModels[0].icon = selectedImage
selectedCharacterImage = plantModels[0].icon
let water_Type = userDefaults.string(forKey: "Water_Type")
switch water_Type
{
case "plant": // return plant data
selectedImageName = getImageName(for: selectedImage)
userDefaults.set(["section": indexPath.section, "item": indexPath.row], forKey: "selectedPlantIndex")
case "animal": // return animal data
selectedImageName = getImageName(for: selectedImage)
userDefaults.set(["section": indexPath.section, "item": indexPath.row], forKey: "selectedAnimalIndex")
default:
break
}
}
} else {
// Handle the case where cell is nil
print("Cell is nil for indexPath: (indexPath)")
}
default:
break
}
settingsTView.reloadData()
}
the check mark should show when no cell is selected
New contributor
iOS Developer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.