我想制作一个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”
为最后一行。
答案 0 :(得分:9)
TTTAttributedLabel在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")
}
}
答案 1 :(得分:8)
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)