swift: The HTML data converted to NSAttributed string doesn't make the links clickable in label

前端 未结 1 1800
悲&欢浪女
悲&欢浪女 2021-01-28 07:54

I have a text in HTML format. I am using the property of NSAttributed string to parse it. It pareses the text nicely and displays on the label. However, the parsing of the ancho

相关标签:
1条回答
  • 2021-01-28 08:26

    From your line:

    simpleTextLabel.attributedText = text.htmlToAttributedString
    

    We can assume that simpleTextLabel is a UILabel.

    It's basic behavior from a UILabel to not be "interactable". You can add a tap gesture on it, but it transform it as a UIButton.

    There are some tricks to make it possible with a UILabel, find where exactly it has been tapped, check if there is a link, etc. Looking for "UILabel Clickable": Create tap-able "links" in the NSAttributedString of a UILabel? etc. There are even a few third party libs.

    I (in my humble opinion) consider it as a "hack".

    There is a good WWDC 2018 Session: TextKit Best Practices. At 2:34, it explains that if you need to interact with a shown text, prefers UITextView over UILabel.

    There is a UITextViewDelegate method just for that: textView(_:shouldInteractWith:in:interaction:)

    Note that there a small differences in the rendering of a UITextView and a UILabel. If you superpose them, they won't have the same "start point", the layout is a little different. However, with small changes, it can be the same (for instance: How can I make a UITextView layout text the same as a UILabel?).

    Note also that according to the small modifications of a UITextView into a UILabel visual rendering, the user won't notice the difference (and that's in fact what matters, beside that using native methods of the UITextView/UITextViewDelegate make it easily understandable afterwards by another developer, or in a few months if you need to do a small modification).

    0 讨论(0)
提交回复
热议问题