mninety5 mninety5 - 3 years ago 299
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]) {


for i in selectedIndices {

if selectedInterests.count > 3 {
print("limit reached")

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 {

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