繁体   English   中英

数组达到限制后禁用选择

[英]Disable selection after an array has reached a limit

我正在使用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显示此示例。 如何通过两者都不实现呢?

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

var maxTagsSelected = 3

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

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

尝试这个..

var selectedInterests = [Int]()

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

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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