我想用一些带有可点击链接的文本制作UILabel.不是链接到网页,而是像我使用UIButton那样的操作.所以我使用了TTTAttributedLabel,它与Objective C完美配合.现在我想在
Swift中做同样的事情,所以我写了下面的代码:
self.someLabel.text = NSLocalizedString("Lost? Learn more.",comment: "") let range = self.someLabel.text!.rangeOfString(NSLocalizedString("Learn more",comment:"")) self.someLabel.addLinkToURL (NSURL(string:"action://Learn more"),withRange:NSRange (range))
解决方法
String.rangeOfString返回Range,但NSString.rangeOfString返回NSRange.所以下面的代码应该工作:
let name = "tomo" let string = "My name is \(name)" label.text = string let nsString = string as NSString let range = nsString.rangeOfString(name) let url = NSURL(string: "action://users/\(name)")! label.addLinkToURL(url,withRange: range)