簡體   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