在阵列达到限制后禁用选择

时间:2017-11-24 11:52:47

标签: ios swift

我正在使用HTagView库来显示标记列表。我已填充标签,现在我想限制最多3的选择。这是我尝试这个的地方:

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

我试图删除数组的最后一项,但这也不起作用。大多数示例都是基于表或collectionView的indexPath显示此示例。如何用两者中的任何一个来实现它?

2 个答案:

答案 0 :(得分:2)

如果已经选择的标签数量大于3,您需要做的就是立即取消选择标签。我还会将金额作为变量,您可以轻松更改以下值:

var maxTagsSelected = 3

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

变量maxTagsSelected将始终是selectedIndices中最后一个元素的索引。

答案 1 :(得分:0)

试试这个..

var selectedInterests = [Int]()

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

    selectedInterests.removeAll()
    selectedInterests = selectedIndices[0..<3]

}