[英]Custom Attributed string action in swift
I want to make the attributed string action in swift. 我想在swift中进行属性字符串操作。 I want append my custom variable to table view cell data.
我想将自定义变量附加到表视图单元格数据。
I added colour and line also for that string, now i want to add the link for that added attributed string. 我也为该字符串添加了颜色和线条,现在我想为添加的属性字符串添加链接。
Please find my code with the following. 请使用以下代码查找我的代码。
I add this code into cell for row at Index path. 我将此代码添加到索引路径中的行的单元格中。
let value = NSMutableAttributedString(string: " tap here.", attributes:[NSAttributedStringKey.link: URL(string: "http://www.google.com")!]).withTextColor(UIColor.disSatifyclr).withUnderlineColor(UIColor.disSatifyclr).withUnderlineStyle(.styleSingle)
if (cell.desclbl.text?.contains("more about donating, "))! {
let description = descriptions[indexPath.section][indexPath.row]
let attributedString = NSMutableAttributedString(string: description)
attributedString.append(value)
cell.desclbl.attributedText = attributedString
}
Here you can handle action using UITextView instead of UILabel on tap of string 在这里你可以使用UITextView而不是UILabel来处理动作
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
textView.attributedText = prepareLink()
textView.tintColor = UIColor.black
textView.isSelectable = true
textView.isEditable = false
textView.delegate = self
}
func prepareLink() -> NSMutableAttributedString {
let formattedString = NSMutableAttributedString(string: " tap here ")
let linkAttribute = [
NSAttributedString.Key.foregroundColor: UIColor.green,
NSAttributedString.Key.underlineColor: UIColor.green,
NSAttributedString.Key.underlineStyle: 1,
NSAttributedString.Key.link: URL(string: "http://www.google.com")!
] as [NSAttributedString.Key : Any]
formattedString.addAttributes(linkAttribute, range: NSMakeRange(0, formattedString.length))
return formattedString
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
if (URL.absoluteString == "http://www.google.com") {
// Do Something
}
return true
}
}
Note: If you have to continue with UILabel then you have to implement UITapGesture to handle action. 注意:如果必须继续使用UILabel,则必须实现UITapGesture来处理操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.