How to find substring frame inside UILabel in swift 4?

I have a UILabel that contains some string like

"I agree to the terms and conditions"

.

Now, by clicking on "Conditions", I want to get it so that I can add a button to this position at runtime to detect a touch on a particular word. I'm not sure how I can detect?

0
ios uilabel swift
source share
1 answer

We cannot make uilabel properties available as you want, in your case we can use TextView for such a property

my class:

import UIKit class TextViewVC: UIViewController { @IBOutlet weak var textView: UITextView! let termsAndConditionsURL = "termsandconditions" override func viewDidLoad() { super.viewDidLoad() textView.delegate = self // Do any additional setup after loading the view. let str = "I agree to below Terms & Condistions" let attributedString = NSMutableAttributedString(string: str) let foundRange = attributedString.mutableString.range(of: "Terms & Condistions") attributedString.addAttribute(.foregroundColor, value: UIColor.blue, range: foundRange) attributedString.addAttribute(.underlineStyle , value: NSUnderlineStyle.styleSingle.rawValue, range: foundRange) attributedString.addAttribute(.link, value: termsAndConditionsURL, range: foundRange) textView.attributedText = attributedString } } extension TextViewVC : UITextViewDelegate { func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool { if (URL.absoluteString == termsAndConditionsURL) { print("Need an action here") } else { print("No") } return false } } 

My storyBoard to create a textView:

enter image description here

Simulator output

enter image description here

Console exit

enter image description here

+1
source share

All Articles