我有一个包含一些字符串的 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:
模拟器输出
控制台输出
关于ios - 如何在 swift 4 的 UILabel 中找到子字符串的框架?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47385251/