如何在swift 4中找到UILabel内的子串的框架?

时间:2017-11-20 04:49:57

标签: ios swift uilabel

我有一个UILabel,其中包含一些字符串

  

"我同意以下条款& Condistions"

现在点击"条款&条件"我想得到它的框架,这样我就可以在运行时在该位置添加一个按钮来检测特定单词的触摸。我不确定我怎么能发现?

1 个答案:

答案 0 :(得分:1)

我们无法根据您的需要制作uilabel可访问的属性,我们可以在这里使用TextView来获取此类属性

我的班级:

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
    }
}

我的故事板用于创建textView:

enter image description here

模拟器输出

enter image description here

控制台输出

enter image description here