Swift-如何使UILabel像主题标签一样可点击并区分相同的文本? [英] Swift - How to make UILabel clickable like hashtag and distinguish the same text?
问题描述
我有一个UIlabel,其文本类似于以下
I have a UIlabel and it's text like following
label.text = "#fun #fun #google #youtube"
我想使UILabel可单击并打开其网址。
I want to make the UILabel clickable and open it's url.
我也制作字典来设置它的键和值。
I also make the dictionary to set it's keys&values.
var dic:[String:String] = ["https://www.yahoo.com.tw/" :"fun",
"https://www.facebook.com.tw/":"fun",
"https://www.google.com.tw/" :"Google",
"https://www.youtube.com/" :"Youtube"
]
//How about change it's type to array?
var arr:[[String:String]] = [["https://www.yahoo.com.tw/" :"fun"],
["https://www.facebook.com.tw/":"fun"],
["https://www.google.com.tw/" :"Google"],
["https://www.youtube.com/" :"Youtube"]
]
如何将乐趣分隔为加载不同的url当我单击 #fun吗?
How to seprate "fun" to load different url When I click "#fun"?
我使用第三库 ActiveLabel.swift 来实现UILabel可点击。 / p>
I use third-library ActiveLabel.swift to achieve UILabel clickable.
label.handleHashtagTap({ (string) in
//do something.
let keys = self.dic.allKeys(forValue: "#\(string) ")
print("--> keys: \(keys)")
})
extension Dictionary where Value: Equatable {
func allKeys(forValue val: Value) -> [Key] {
return self.filter { $1 == val }.map { $0.0 }
}
}
推荐答案
使用字典数组,然后执行类似的操作
Use array of dictionary and then do something like this
let dataArray = [["https://www.yahoo.com.tw/" :"fun"],
["https://www.facebook.com.tw/":"fun"],
["https://www.google.com.tw/" :"Google"],
["https://www.youtube.com/" :"Youtube"]
]
您可以运行for循环以显示所有值您的标签:
And you can run a for loop to show all the values on your label :
for i in 0..<dataArray.count{
let label = UILabel()
label.tag = i
for (key,value) in dataArray[i]{
print(key, value)
label.text = "#\(value)"
}
// then add tap gesture to that label
}
您必须动态创建标签d每个标签都会有一个轻击手势。
You have to create labels dynamically and each label will have a tap gesture.
在轻击手势上,您可以获得标签的标签,因此可以根据标签从dataArray中获取被点击的值
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.
这篇关于Swift-如何使UILabel像主题标签一样可点击并区分相同的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!