TTTAttributedLabel中的可点击链接与Swift
我想用一些带有可点击链接的文本制作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))
但是,我不能使链接在Swift
工作。 我收到错误: “Missing argument for parameter 'host' in call”
为最后一行。
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)
TTTAttributedLabel lable in swift 4
import TTTAttributedLabel @IBOutlet weak var attributedLable: TTTAttributedLabel! override func viewDidLoad() { super.viewDidLoad() self.setup() } func setup(){ attributedLable.numberOfLines = 0; let strTC = "terms and conditions" let strPP = "privacy policy" let string = "By signing up or logging in, you agree to our \(strTC) and \(strPP)" let nsString = string as NSString let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineHeightMultiple = 1.2 let fullAttributedString = NSAttributedString(string:string, attributes: [ NSAttributedStringKey.paragraphStyle: paragraphStyle, NSAttributedStringKey.foregroundColor: UIColor.black.cgColor, ]) attributedLable.textAlignment = .center attributedLable.attributedText = fullAttributedString; let rangeTC = nsString.range(of: strTC) let rangePP = nsString.range(of: strPP) let ppLinkAttributes: [String: Any] = [ NSAttributedStringKey.foregroundColor.rawValue: UIColor.blue.cgColor, NSAttributedStringKey.underlineStyle.rawValue: false, ] let ppActiveLinkAttributes: [String: Any] = [ NSAttributedStringKey.foregroundColor.rawValue: UIColor.blue.cgColor, NSAttributedStringKey.underlineStyle.rawValue: false, ] attributedLable.activeLinkAttributes = ppActiveLinkAttributes attributedLable.linkAttributes = ppLinkAttributes let urlTC = URL(string: "action://TC")! let urlPP = URL(string: "action://PP")! attributedLable.addLink(to: urlTC, with: rangeTC) attributedLable.addLink(to: urlPP, with: rangePP) attributedLable.textColor = UIColor.black; attributedLable.delegate = self; } func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith url: URL!) { if url.absoluteString == "action://TC" { print("TC click") } else if url.absoluteString == "action://PP" { print("PP click") } }
输出看起来像下面的截图