How to find the frame of substring inside a UILabel in swift 4?

ⅰ亾dé卋堺 提交于 2019-12-11 07:29:40

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!