简体   繁体   中英

How to get different key with single value in dictionary by Swift 3

I have a clickable UILabel.
And the label text show all dictionary values.
Then when I click, I want to use value to check back the keys.
But if I just have a single value, how to separate keys to each different value label.

像这样的图像。

//Dictionary Data
self.finalDic = ["11defba4d092ggf00e0fdb5": "@user5 ", "114defba4d092ggf00e0fdb6": "@user6 ", "114defba4d092ggf00e0fdb1": "@user1 ", "114defba4d092ggf00e0fdb3": "@user1 ", "114defba4d092ggf00e0fdb4": "@user4 ", "114defba4d092ggf00e0fdb2": "@user1 "]

When I click the first @user1, I will get a key(114defba4d092ggf00e0fdb1).
Then I click the second @user1, I will get another key(114defba4d092ggf00e0fdb3).
Final I click the third @user1, I will get the last key(114defba4d092ggf00e0fdb2).

What should I do to distribute them to a different label?

label.handleMentionTap({ (string) in

        let keys = self.finalDic.allKeys(forValue: "@\(string) ")
        if keys.count > 1 {
            print("--> keys > 1 : \(keys)")
        }else{
            print("--> keys: \(keys)")
        }
})

You can also make and array which have multiple key-value pairs, and them you can give tags to your label and on tap you can get the value directly based on a tag.

So your dataArray will be like this :

let dataArray = [ ["11defba4d092ggf00e0fdb5": "@user5 "], ["114defba4d092ggf00e0fdb6": "@user6 "], ["114defba4d092ggf00e0fdb1": "@user1 "], ["114defba4d092ggf00e0fdb3": "@user1 "], ["114defba4d092ggf00e0fdb4": "@user4 "], ["114defba4d092ggf00e0fdb2": "@user1 "]]

Anf you can run a for loop to show all the values on your label :

for i in 0..<dataArray.count{
    yourLabel.tag = i
    for (key,value) in dataArray[i]{
        print(key, value)
        yourLabel.text = value
    }

}

On tap gesture you can get the tag of the label and thus you can get the tapped value from your dataArray based on your tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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