0

enter image description here

Hey guys how do I make a link clickable in a table view cell as shown in the image link above ? The information is from a Json File.

func tableView( tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "albumID", for: indexPath)
    let album :[String:Any] = albums[indexPath.row]

    cell.textLabel?.text = album["collectionName"] as? String
    cell.detailTextLabel?.text = album["artistName"] as? String


    return cell
}
koen
  • 5,383
  • 7
  • 50
  • 89
Mayowa Paul
  • 65
  • 1
  • 6
  • Does this answer your question? [How can I make a clickable link in an NSAttributedString?](https://stackoverflow.com/questions/21629784/how-can-i-make-a-clickable-link-in-an-nsattributedstring) – koen Jul 06 '20 at 13:46

2 Answers2

0

You need to have UITextView as detailTextLabel

 attributedString.addAttribute(.link, value: "https://developer.apple.com", range: NSRange(location: 30, length: 50))

    cell.detailTextLabel?.attributedText = attributedString

and then implement this method

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        UIApplication.shared.open(URL)
        return false
    }
Jawad Ali
  • 13,556
  • 3
  • 32
  • 49
0

You can use the below-mentioned statements to make a link of textView or label either inside tableView, collection view, or using them separately inside viewController.

If you are using textView then you can use this code mentioned below:-

let attributedString = NSMutableAttributedString(string: "Just click here to `register")
let url = URL(string: "https://www.apple.com")!

// Set the 'click here' substring to be the link
attributedString.setAttributes([.link: url], range: NSMakeRange(5, 10))

self.textView.attributedText = attributedString
self.textView.isUserInteractionEnabled = true
self.textView.isEditable = false

// Set how links should appear: blue and underlined
self.textView.linkTextAttributes = [
.foregroundColor: UIColor.blue,
.underlineStyle: NSUnderlineStyle.single.rawValue
]

or if you are using labels then you can use this code mentioned below:-

var attributedString = NSMutableAttributedString(string: "String with a link", ``attributes: nil)
let linkRange = NSRange(location: 14, length: 4) // for the word "link" in the string above

let linkAttributes = [
NSAttributedString.Key.foregroundColor: UIColor(red: 0.05, green: 0.4, blue: 0.65, alpha: 1.0),
NSAttributedString.Key.underlineStyle: NSNumber(value: NSUnderlineStyle.single.rawValue)
]
attributedString.setAttributes(linkAttributes, range: linkRange)

// Assign attributedText to UILabel
label.attributedText = attributedString```
Apps Maven
  • 1,314
  • 1
  • 4
  • 17