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()
}
}
}
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.