ios - 如何在 swift 4 的 UILabel 中找到子字符串的框架?

标签 ios swift uilabel

我有一个包含一些字符串的 UILabel

"I agree to below Terms & Condistions"

.

现在单击“条款和条件”我想获取它的框架,以便我可以在运行时在该位置添加一个按钮以检测对特定单词的触摸。我不确定如何检测?

最佳答案

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

我的类(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
    }
}

我创建一个 textView 的 Storyboard:

enter image description here

模拟器输出

enter image description here

控制台输出

enter image description here

关于ios - 如何在 swift 4 的 UILabel 中找到子字符串的框架?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47385251/

相关文章:

iphone - 从关卡深处的字典中删除一个项目

ios - 未调用方法 'application:openURL:options:'

ios - 切换到横向模式时约束变化不更新

ios - 如何在 Swift 中自动移动到下一个 UITextField

ios - 如何在 iOS 中枚举家庭视频?

ios - Xcode6-Beta3 更新后,无法使用 Swift 访问键盘信息

ios - 如何将 UITableViewCell 中的值(Stepper)解析到主视图 Controller ?

ios - 为什么 UITextView 会合并之前设置的 attributedText 的属性?

ios - UILabel文本对齐时英语和希伯来语混合为文本吗?

ios - 为什么UILabel TapGesture 只能在标签初始化后工作?