Create tap-able “links” in the NSAttributedString of a UILabel?

前端 未结 30 2605
半阙折子戏
半阙折子戏 2020-11-22 02:07

I have been searching this for hours but I\'ve failed. I probably don\'t even know what I should be looking for.

Many applications have text and in this text are web

30条回答
  •  既然无缘
    2020-11-22 02:43

    I follow this version,

    Swift 4:

    import Foundation
    
    class AELinkedClickableUILabel: UILabel {
    
        typealias YourCompletion = () -> Void
    
        var linkedRange: NSRange!
        var completion: YourCompletion?
    
        @objc func linkClicked(sender: UITapGestureRecognizer){
    
            if let completionBlock = completion {
    
                let textView = UITextView(frame: self.frame)
                textView.text = self.text
                textView.attributedText = self.attributedText
                let index = textView.layoutManager.characterIndex(for: sender.location(in: self),
                                                                  in: textView.textContainer,
                                                                  fractionOfDistanceBetweenInsertionPoints: nil)
    
                if linkedRange.lowerBound <= index && linkedRange.upperBound >= index {
    
                    completionBlock()
                }
            }
        }
    
    /**
     *  This method will be used to set an attributed text specifying the linked text with a
     *  handler when the link is clicked
     */
        public func setLinkedTextWithHandler(text:String, link: String, handler: @escaping ()->()) -> Bool {
    
            let attributextText = NSMutableAttributedString(string: text)
            let foundRange = attributextText.mutableString.range(of: link)
    
            if foundRange.location != NSNotFound {
                self.linkedRange = foundRange
                self.completion = handler
                attributextText.addAttribute(NSAttributedStringKey.link, value: text, range: foundRange)
                self.isUserInteractionEnabled = true
                self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(linkClicked(sender:))))
                return true
            }
            return false
        }
    }
    

    Call Example:

    button.setLinkedTextWithHandler(text: "This website (stackoverflow.com) is awesome", link: "stackoverflow.com") 
    {
        // show popup or open to link
    }
    

提交回复
热议问题