0

I want to make the attributed string action in 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
        }
Bharti Rawat
  • 1,949
  • 21
  • 32
srikanth kumar
  • 77
  • 1
  • 10

1 Answers1

0

Here you can handle action using UITextView instead of UILabel on tap of string

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.

Bhavik Modi
  • 1,517
  • 14
  • 29