Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Link within label in Swift

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?

like image 408
KevinB Avatar asked Jun 05 '17 09:06

KevinB


People also ask

What is label in Swift?

Label is a user interface item in SwiftUI which enables you to display a combination of an image (icon, SF Symbol or other) and a text label in a single UI element.


2 Answers

For such a case, instead of adding it as a UILabel component, I would rather use UITextView, because it has dataDetectorTypes property:

The types of data converted to tappable URLs in the text view.

You can use this property to specify the types of data (phone numbers, http links, and so on) that should be automatically converted to URLs in the text view. When tapped, the text view opens the application responsible for handling the URL type and passes it the URL. Note that data detection does not occur if the text view's isEditable property is set to true.

So, you can implement it as:

// as mentioned in the documentation, make sure to let it be uneditable:
textView.isEditable = false
textView.dataDetectorTypes = .link

For your case, I assume that it shall be .link. I would also suggest to check the other options for the UIDataDetectorTypes.

like image 104
Ahmad F Avatar answered Nov 14 '22 08:11

Ahmad F


Use Active-Label https://github.com/optonaut/ActiveLabel.swift Make a UILabel named label

 let customType = ActiveType.custom(pattern: "\\sjohncena\\b") 
 label.enabledTypes.append(customType3)
 label.handleCustomTap(for: customType) { self.alert("Custom type", message: $0) }

 func alert(_ title: String, message: String) {
        let vc = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        vc.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
        present(vc, animated: true, completion: nil)
    }

where johncena is string which is clickable. see https://github.com/optonaut/ActiveLabel.swift/blob/master/ActiveLabelDemo/ViewController.swift

like image 26
Jack Avatar answered Nov 14 '22 10:11

Jack