I want to make a UILabel
with some text with a click-able links in it. Not links to webpages but to actions like I do with an UIButton
. So I used
TTTAttributedLabel lable in swift 4.2
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")
}
}
Out put is look like below screenshot