如何将 link 添加到 swift 中的 UILabel?
How do I add a link to a UILabel in swift?
我有一个标签,上面写着“单击此处”。当用户点击“此处”时,我希望它将我的用户带到 https://www.google.com。我该怎么做呢?提前致谢!
两种方法。
- 点击手势 - UITapGestureRecognizer
// considering you have a UILabel is added to your screen and you have formatted the label to look like a link.
let labelTap = UITapGestureRecognizer(target: self, action: #selector(self.linkLabelTapped(_:)))
self.linkLabel.isUserInteractionEnabled = true
self.linkLabel.addGestureRecognizer(labelTap)
@objc func linkLabelTapped(_ sender: UITapGestureRecognizer) {
print("linkLabelTapped")
}
- 不要使用 UILabel,而是使用具有 link 识别的 UITextView,默认情况下会为您提供格式设置。
linkTextView.userInteractionEnabled = true
linkTextView.selectable = true
linkTextView.dataDetectorTypes = .Link
linkTextView.text = "https://www.google.com."
我有一个标签,上面写着“单击此处”。当用户点击“此处”时,我希望它将我的用户带到 https://www.google.com。我该怎么做呢?提前致谢!
两种方法。
- 点击手势 - UITapGestureRecognizer
// considering you have a UILabel is added to your screen and you have formatted the label to look like a link.
let labelTap = UITapGestureRecognizer(target: self, action: #selector(self.linkLabelTapped(_:)))
self.linkLabel.isUserInteractionEnabled = true
self.linkLabel.addGestureRecognizer(labelTap)
@objc func linkLabelTapped(_ sender: UITapGestureRecognizer) {
print("linkLabelTapped")
}
- 不要使用 UILabel,而是使用具有 link 识别的 UITextView,默认情况下会为您提供格式设置。
linkTextView.userInteractionEnabled = true
linkTextView.selectable = true
linkTextView.dataDetectorTypes = .Link
linkTextView.text = "https://www.google.com."