I would like to do that in my app :
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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With