ios 设置富文本能够点击
在 iOS 中,可以通过给富文本添加点击事件来实现点击功能。以下是一种常见的方法:
-
创建一个富文本字符串 NSAttributedString,并设置需要显示的文本内容和属性。
-
使用 UITextView 或 UILabel 来显示富文本字符串。
-
为 UITextView 或 UILabel 添加手势识别器 UITapGestureRecognizer。
-
在手势识别器的回调方法中,获取点击的位置,并通过 NSLayoutManager 的方法来判断点击的位置是否在富文本的某个区域内。
-
如果点击的位置在富文本的区域内,可以执行相应的操作,比如打开一个链接、显示一个弹窗等。
下面是一个简单的示例代码:
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// 创建富文本字符串
let attributedString = NSMutableAttributedString(string: "点击这里打开链接")
attributedString.addAttribute(.link, value: "https://www.example.com", range: NSRange(location: 2, length: 2))
// 设置文本内容
textView.attributedText = attributedString
// 添加点击手势识别器
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
textView.addGestureRecognizer(tapGesture)
}
@objc func handleTap(_ gesture: UITapGestureRecognizer) {
let layoutManager = textView.layoutManager
let location = gesture.location(in: textView)
let characterIndex = layoutManager.characterIndex(for: location, in: textView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
// 获取点击的属性
if let link = textView.attributedText.attribute(.link, at: characterIndex, effectiveRange: nil) as? String {
// 执行点击操作
print("点击了链接:\(link)")
}
}
}
在上面的示例中,我们创建了一个 UITextView,并设置了一个富文本字符串,其中 "点击这里" 这两个字可以点击。点击后会在控制台输出链接地址。
需要注意的是,如果想要在 UILabel 中实现富文本点击功能,需要将 UILabel 的 userInteractionEnabled 属性设置为 true,使其能够接收用户交互事件
原文地址: https://www.cveoy.top/t/topic/hNmP 著作权归作者所有。请勿转载和采集!