问题
I have a UILabel which contains some string as
"I agree to below Terms & Condistions"
.
Now on click of "Terms & conditions" i want to get it's frame so that i can add a button on that position at run time to detect the touch on particular word. By i am not sure how can i detect ?
回答1:
We can't make a uilabel accessible properties as you want in your case we can make use of TextView here for such 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 for creating a textView :
Simulator output
Console Output
来源:https://stackoverflow.com/questions/47385251/how-to-find-the-frame-of-substring-inside-a-uilabel-in-swift-4