快速的自定义属性字符串操作

时间:2019-05-30 08:41:29

标签: swift tableview action nsattributedstring

我想迅速做出归因于字符串的动作。我想将自定义变量附加到表格视图单元格数据中。

我也为该字符串添加了颜色和线条,现在我想为该添加的属性字符串添加链接。

请在下面找到我的代码。

我将此代码添加到索引路径中行的单元格中。

 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
        }

1 个答案:

答案 0 :(得分:0)

在这里,您可以在敲击字符串时使用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
    }
}

注意:如果必须继续使用UILabel,则必须实现UITapGesture来处理操作。