mninety5 mninety5 - 10 months ago 126
iOS Question

Disable selection after an array has reached a limit

I'm using a HTagView library to display a list of tags. I have populated the tags and now I want to limit the selection of up to 3. Here is where I'm attempting this:

var selectedInterests = [Int]()

func tagView(_ tagView: HTagView, tagSelectionDidChange selectedIndices: [Int]) {

selectedInterests.removeAll()

for i in selectedIndices {
selectedInterests.append(i)

if selectedInterests.count > 3 {
print("limit reached")
selectedInterests.removeLast()
tagView.reloadData()
}
}
}


I've attempted to remove the last item of the array but this also doesn't work. Most examples are showing this example based on the indexPath of a table or collectionView. How do I achieve it with out either of the two?

Answer Source

All you need to do is to immediately deselect the tag if the amount of already selected tags is greater than 3. I would also make the amount as a variable that you can easily change the value of:

var maxTagsSelected = 3

func tagView(_ tagView: HTagView, tagSelectionDidChange selectedIndices: [Int]) {
    if selectedIndices.count > maxTagsSelected {
        tagView.deselectTagAtIndex(selectedIndices[maxTagsSelected])
    }
}

The variable maxTagsSelected will always be the index of the last element in selectedIndices.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download