简体   繁体   中英

Removing CollectionView cell class from array?

I am creating a wizard using UICollectionView with an array of CollectionViewCells:

var viewCells:[BaseCVCell] = [createEventSubjectSearch(), createEventEventForm()] 

This array is dynamically added to based on a series of UISwitch's that the user controls. I can add to the array fine using the code below, however I can't seem to remove an item when a user turns the switch off.

func switchToggled(sender : UISwitch) {

    if sender == createDiarySwitch {
        if sender.isOn {
            parentClass?.viewCells.append(createEventDeferEvent())
        } else {
            if let i = parentClass?.viewCells.index(where: { $0 == createEventDeferEvent() }) {
                parentClass?.viewCells.remove(at: i)
            }
        }
    }

    if sender == createDeferredSwitch {
        if sender.isOn {
            parentClass?.viewCells.append(createEventDiariseEvent())
        } else {
            if let i = parentClass?.viewCells.index(where: { $0 == createEventDiariseEvent() }) {
                parentClass?.viewCells.remove(at: i)
            }
        }
    }

    parentClass?.wizardCollectionView.reloadData()

}

I have tried the above code, as well as:

if let index = parentClass?.viewCells.index(of: createEventDiariseEvent()) {
    parentClass?.viewCells.remove(at: index)
}

Neither approach works (no errors, the code just never returns a value). I'd like to try and avoid naming elements where possible. Is there a way to do this?

Thanks for your answers, DonMag

I've achieved the desired functionality by instanciating the two dynamic cells in the main class:

let diariseCell : createEventDiariseEvent()

and then in the loop calling as thus:

if sender == createDiarySwitch {
    if sender.isOn {
        parentClass?.viewCells.append((parentClass?.diariseCell)!)
    } else {
        if let i = parentClass?.viewCells.index(where: { $0 == parentClass?.diariseCell }) {
            print("Found cell reference at index \(i)")
            parentClass?.viewCells.remove(at: i)
        }
    }
}

Works a charm now. Amazing what another pair of eyes can pick out!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM