Link within label in Swift

Viewed 41165

I would like to do that in my app :

enter image description here

The label is like : username comment

I don't know how to add the "button" within the label; I found this library but I'm not sure it will work? https://github.com/optonaut/ActiveLabel.swift

Maybe use it by creating a regex for the first word? What do you think?

4 Answers

Swift 5

You can use UITextView and can simply use this way.

class ViewController: UIViewController, UITextViewDelegate {
        @IBOutlet var textView: UITextView!
    
        override func viewDidLoad() {
            let attributedString = NSMutableAttributedString(string: "Want to learn iOS? You should visit the best source of free iOS tutorials!")
            attributedString.addAttribute(.link, value: "https://www.hackingwithswift.com", range: NSRange(location: 19, length: 55))
    
            textView.attributedText = attributedString
        }
    
        func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
            UIApplication.shared.open(URL)
            return false
        }
    }
Related