Home > Software design >  How to present UIAlertController when finished multiple selection in UICollectionView
How to present UIAlertController when finished multiple selection in UICollectionView

Time:12-07

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ShiftCollectionViewCell.identifier, for: indexPath) as? ShiftCollectionViewCell else {
        return UICollectionViewCell()
    }
    let model = shiftSection[indexPath.section].options[indexPath.row]
    cell.configure(withModel: OptionsCollectionViewCellViewModel(id: 0, data: model.title))
    return cell
}

func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
    collectionView.indexPathsForSelectedItems?.filter({ $0.section == indexPath.section }).forEach({ collectionView.deselectItem(at: $0, animated: false) })
    return true
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let model = shiftSection[indexPath.section].options[indexPath.row]
    print(model.title)
    
    if indexPath.section == 2 {
        showAlert()
    }
}

enter image description here

my goal is to show alert when finished multiple selection in collectionview Thankyou in advance :)

CodePudding user response:

Your description is a bit thin so I am guessing/assuming that what you want is kind of; After user selects an item in every section an alert view should be shown.

To achieve this you could have a nullable property for each of possible selection and then check if all of them are set. For instance imagine having

private var timeMode: TimeMode?
private var shift: Shift?
private var startTime: StartTime?

now on didSelectItemAt you would try and fill these properties like:

if indexPath.section == 0 { // TODO: rather use switch statement
    timeMode = allTimeModes[indexPath.row]
} else if indexPath.section == 1 {
    shift = allShifts[indexPath.row]
} ...

then at the end of this method (preferably call a new method) execute a check like

guard let timeMode = self.timeMode else { return }
guard let shift = self.shift else { return }
guard let startTime = self.startTime else { return }

showAlert()

Alternatively

You can use a collection view property indexPathsForSelectedItems to determine what all is selected in a similar way every time user selects something:

guard let timeModeIndex = collectionView.indexPathsForSelectedItems?.first(where: { $0.section == 0 })?.row else { return }
guard let shiftIndex = collectionView.indexPathsForSelectedItems?.first(where: { $0.section == 1 })?.row else { return }
guard let startTimeIndex = collectionView.indexPathsForSelectedItems?.first(where: { $0.section == 2 })?.row else { return }

showAlert()

I hope this puts you on the right track.

  • Related