9
4

2 回答 2

17

swift 4.2 中的 TTTAttributedLabel 标签

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: [
        NSAttributedString.Key.paragraphStyle: paragraphStyle,
        NSAttributedString.Key.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] = [
        NSAttributedString.Key.foregroundColor.rawValue: UIColor.blue.cgColor,
        NSAttributedString.Key.underlineStyle.rawValue: false,
        ]
    let ppActiveLinkAttributes: [String: Any] = [
        NSAttributedString.Key.foregroundColor.rawValue: UIColor.blue.cgColor,
        NSAttributedString.Key.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")
        }
    }

输出如下图所示 在此处输入图像描述

于 2018-07-16T12:49:48.187 回答
9

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)
于 2015-01-09T09:28:23.847 回答