johnsena
johnsena

Reputation: 11

How to make NSAttributedString link clickable

I have a requirement to display the numbers as clickable link from a string input(contains alphabets and numerals) and on tap of that number it should open an iOS call dialler and should dials that number.

Below is what I have tried at the moment, to make the number to look like a tappable one and rest all text as normal default text with black color below formattedText var has been defined,

var formattedText: NSAttributedString{
let message = "Hey you can dial up {88 22 333} number for further assistance"
let linkRange = (message as NSString).range(of: fetchNumber) //fetchNumber method returns the content residing inside flower braces..

guard linkRange.location != NSNotFound else {return nil}
let finalString = NSMutableAttributedString(string: message, attributes:[.font: UIFont.scaledFont(from: .baseText16), foregroundColor: .black])
finalString.addAttributes([.foregroundColor: .blue], range: linkRange) 
return finalString 
}

output of above function is: Hey you can dial up 88 22 333 number for further assistance

and to make the number tappable I have tried using this attributed text input to UITextView with dataDetectorType property enabled but it is not working for me :( Is there any way to make it happen with UILabel itself or any sort of UIKit elements, any suggestions is much appreciated in advance, thanks

I have tried using this attributed text input to UITextView with dataDetectorType property enabled but it is not working for me :( Is there any way to make it happen with UILabel itself or any sort of UIKit elements, any suggestions is much appreciated in advance, thanks

Upvotes: 1

Views: 3671

Answers (1)

Jenish
Jenish

Reputation: 477

First of all you need to declare mobile number globally.

var mobileNo = "88 22 333"

Set attributed string for your text and create tappable label.

func setupLabel() {
    
    let fullString = "Hey you can dial up " + mobileNo + " number for further assistance"
    let strNSString: NSString = fullString as NSString
    let rangeNumber = (strNSString).range(of: mobileNo)
    let attribute = NSMutableAttributedString.init(string: fullString)
    attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.lightGray , range: rangeNumber)
    attribute.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 16), range: rangeNumber)
    lblNumber.attributedText = attribute
    
    //Tap Gesture
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(lblNumberTapped))
    lblNumber.addGestureRecognizer(tapGesture)
    lblNumber.isUserInteractionEnabled = true
}

After that declare method of tap gesture.

//MARK: - TapGesture Click events
@objc func lblNumberTapped(_ gesture: UITapGestureRecognizer) {
    self.view.endEditing(true)
    
    let text = self.lblNumber.text ?? ""
    let recoverMobileNumber = (text as NSString).range(of: mobileNo)

    if gesture.didTapAttributedTextInLabel(label: lblNumber, inRange: recoverMobileNumber) {
        if let callUrl = URL(string: "tel://\(mobileNo)"), UIApplication.shared.canOpenURL(callUrl) {
             UIApplication.shared.open(callUrl)
        }

    }
    

}

You need UITapGestureRecognizer extension for detect tap events.

extension UITapGestureRecognizer {
func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool {

    // Create instances of NSLayoutManager, NSTextContainer and NSTextStorage
    let layoutManager = NSLayoutManager()
    let textContainer = NSTextContainer(size: CGSize.zero)
    let textStorage = NSTextStorage(attributedString: label.attributedText!)

    // Configure layoutManager and textStorage
    layoutManager.addTextContainer(textContainer)
    
    textStorage.addLayoutManager(layoutManager)

    // Configure textContainer
    textContainer.lineFragmentPadding = 0.0
    textContainer.lineBreakMode = label.lineBreakMode
    textContainer.maximumNumberOfLines = label.numberOfLines
    let labelSize = label.bounds.size
    textContainer.size = labelSize

    // Find the tapped character location and compare it to the specified range
    let locationOfTouchInLabel = self.location(in: label)
    let textBoundingBox = layoutManager.usedRect(for: textContainer)
    //let textBoundingBox = layoutManager.boundingRect(forGlyphRange: targetRange, in: textContainer)
    let textContainerOffset = CGPoint(x: (labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)
    let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y)
    let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)

    return NSLocationInRange(indexOfCharacter, targetRange)
}
}

Upvotes: 1

Related Questions