使用Swift制作可点击的UILabel

我想使用Swift在UILabel文本中设置特定字可点击。

可能吗?

如果有多个标签在这里,我怎么能检测到哪个单词被按下?

你不能用简单的标签。

在github有可用的库。

https://github.com/TTTAttributedLabel/TTTAttributedLabel

从这里你可以使用名为yourLabel.addLinkToURL()的方法

 class ViewController: UIViewController , TTTAttributedLabelDelegate{ @IBOutlet var lbl: TTTAttributedLabel! override func viewDidLoad() { super.viewDidLoad() var str : NSString = "Hello this is link" lbl.delegate = self lbl.text = str as String var range : NSRange = str.rangeOfString("link") lbl.addLinkToURL(NSURL(string: "http://github.com/mattt/")!, withRange: range) } func attributedLabel(label: TTTAttributedLabel!, didSelectLinkWithURL url: NSURL!) { UIApplication.sharedApplication().openURL(url) } } 

在这里输入图像说明

SWIFT 3.0

  privacyLabel.delegate = self let strPolicy : NSString = "Agree to the Terms & Conditions" privacyLabel.text = strPolicy as String let range1 : NSRange = strPolicy.range(of: "Terms & Conditions") privacyLabel.addLink(to: URL(string: "http://Terms.com")!, with: range1) func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith url: URL!) { print("url \(url)") // UIApplication.sharedApplication().openURL(url) } 

我想分享我的图书馆https://github.com/psharanda/Atributika

它包含现代TTTAtributedLabel +强大的方法检测和样式不同的东西,如标签,主题标签,提及等(所有的东西都可以点击)

一些代码来显示它是如何工作的:

  let link = Style .font(.boldSystemFont(ofSize: 14)) .foregroundColor(.black) .foregroundColor(.red, .highlighted) let tos = link.named("tos") let pp = link.named("pp") let all = Style .font(.systemFont(ofSize: 14)) .foregroundColor(.gray) let text = "<tos>Terms of Service</tos> and <pp>Privacy Policy</pp>" .style(tags: tos, pp) .styleAll(all) let tosLabel = AttributedLabel() tosLabel.textAlignment = .center tosLabel.attributedText = text tosLabel.onClick = { label, detection in switch detection.type { case .tag(let tag): switch tag.name { case "pp": print("Privacy Policy clicked") case "tos": print("Terms of Service clicked") default: break } default: break } } view.addSubview(tosLabel)