swift - swift 中的自定义属性字符串操作

标签 swift tableview action nsattributedstring

我想快速执行属性字符串操作。我想将自定义变量附加到 TableView 单元格数据中。

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

请使用以下内容找到我的代码。

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

 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
        }

最佳答案

在这里,您可以在点击字符串时使用 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 来处理操作。

关于swift - swift 中的自定义属性字符串操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56374655/

相关文章:

swift - 如何在 swift 中将特定类(符合约束)类型转换为泛型?

swift - 当我以编程方式添加按钮和标题时,为什么按钮和标题没有显示在导航栏上?

ios - swift 3 ios tableview 按单元格滚动

asp.net-mvc - 在每个 Controller 操作上注入(inject) javascript - asp.net mvc

Java - 用于 HTML JTextPane CSS 的 FontSizeAction

ios - 来自 iOS 设备的 Azure Blob 存储 : Server failed to authenticate the request

ios - 使用 swift 从 firebase 中的所有 child 获取数据

ios - 在自定义单元格中编辑 UITextView 时调用 textViewDidBeginEditing

java - 如何正确使用 PropertyValueFactory?

javascript - 每次新点击都有新 Action