0

If I click on the first username "Kelly Kapoor" it should redirect to another page and when I click on the second username "Jim Halpert" it should redirect to another page.

I've tried UITapGestureRecognizer but it only helps if I want to redirect only one username. but as I said I want both of them to redirect to a different location. Here I've combined both the username and added a gesture recognizer on it. but I want the same thing with both of them separately.

func setLikedNotificationsValue(){
    let userNames = ["Kelly Kapoor", "Jim Halpert"]
    let userNamesString = userNames.joined(separator: ", ")
    let likedNotification = "\(userNamesString) they liked your video"
    let rangeUserNames = likedNotification.range(of: userNamesString)!
    let userNamesRange = NSRange(rangeUserNames, in: likedNotification)
    let attributedLikedNotification = NSMutableAttributedString(string: likedNotification)
    attributedLikedNotification.setAttributes([NSAttributedString.Key.foregroundColor: UIColor.white,NSAttributedString.Key.font: UIFont(name: "Inter-SemiBold", size: 14)!], range: userNamesRange)
    lblNotificationMessage.isUserInteractionEnabled = true
    lblNotificationMessage.addGestureRecognizer(UITapGestureRecognizer(target:self, action: #selector(tapLabel(gesture:))))
    imgUserProfileOne?.image = UIImage(named: "tempProfile")
    imgUserProfileTwo?.image = UIImage(named: "8")
    lblNotificationMessage?.attributedText = attributedLikedNotification
    imgLikedPost?.image = UIImage(named: "2")
}

@objc func tapLabel(gesture: UITapGestureRecognizer) {
    
    let userNames = ["Kelly Kapoor", "Jim Halpert"]
    let userNamesString = userNames.joined(separator: ", ")
    let likedNotification = "\(userNamesString) they liked your video"
    let rangeUserNames = likedNotification.range(of: userNamesString)!
    let userNamesRange = NSRange(rangeUserNames, in: likedNotification)
    for userName in userNames {
        print(userName.count)
    }
    if gesture.didTapAttributedTextInLabel(label: lblNotificationMessage, inRange: userNamesRange){
        print("you clicked on us")
    } else{
        print("tapped none")
    }
}

Thank You

Look at the image below to get better idea

1 Answers1

0

Look into using UITextView instead of a UILabel. It will provide you with the capability of adding text that is linkable/clickable.

  1. https://developer.apple.com/documentation/uikit/uitextview
  2. https://developer.apple.com/documentation/uikit/uitextview/1618632-linktextattributes
let descriptionTextView = UITextView()
descriptionTextView.delegate = self
descriptionTextView.attributedText = attributedString
descriptionTextView.linkTextAttributes = [.underlineStyle: NSUnderlineStyle.single.rawValue]
descriptionTextView.dataDetectorTypes = .link
Dee-Bha
  • 439
  • 1
  • 4
  • 8