fphelp
fphelp

Reputation: 1636

Action Label On Text

I have an Xcode project where I want to make an action label for names that is similar to mentions(@) and hashtags(#) labels where its bolded and I can press on it and it will send me to another view controller. I have search aroud for this and have only found cocoa pods that are for mentions and hashtags. How do I implement this?

Example: "Mark Smith liked your photo." Then I will be able to press on "Mark Smith" and it will send me to his profile.

Upvotes: 1

Views: 155

Answers (1)

SolinLiu
SolinLiu

Reputation: 209

Maybe you can replace UILabel with UITextView,run this simple code:

`func addLinkLabel() {
    let textView = UITextView.init(frame: CGRect.init(x: 10, y: 150, width: 400, height: 100))
    self.view.addSubview(textView)

    let attributedString = NSMutableAttributedString.init(string: "Touch me,you'll be sent to another ViewController.")
    attributedString.addAttribute(NSLinkAttributeName, value: "aa", range: NSRange.init(location: 0, length: 8))
    textView.attributedText = attributedString
    textView.font = UIFont.systemFont(ofSize: 17)
    textView.linkTextAttributes = [NSFontAttributeName:UIFont.boldSystemFont(ofSize: 20),
                                   NSForegroundColorAttributeName:UIColor.red]
    textView.isEditable = false
    textView.delegate = self;

}

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    if String(describing: URL) == "aa"  {
        print("Here we go...")
        self.navigationController?.pushViewController(SecondViewController(), animated: true)
        return true
    }
    return false
}

`

Upvotes: 1

Related Questions