背景:
一般点击文本中的链接跳转,可以用 UITextView

用 UITextView 的实现
class ViewController: UIViewController, UITextViewDelegate{
@IBOutlet var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
let link = "https://baike.baidu.com/item/%E5%B0%BC%E5%8F%A4%E6%8B%89%E6%96%AF%C2%B7%E5%87%AF%E5%A5%87/1295347?fromtitle=%E5%B0%BC%E5%8F%A4%E6%8B%89%E6%96%AF%E5%87%AF%E5%A5%87&fromid=415246&fr=aladdin"
let src = "cage 电影,\(link)"
let attributedString = NSMutableAttributedString(string: src)
attributedString.addAttribute(.link, value: link, range: src.range(ns: link))
textView.attributedText = attributedString
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
UIApplication.shared.open(URL)
// 这里放交互事件
return false
}
}
缺点,不是很灵活
- 苹果有自己的设计,链接自动变蓝了
- 阅读不友好,必须是链接,对
link来一个百分号解码,就 gg
不能 "".removingPercentEncoding
本文描述下,使用 Core Text 的两种实现:
都采用 CTFrame 把文本绘制出来;
都是用 func touchesBegan 识别出事件
实现一
每一次点击,计算出点击到的点在文本中的索引值,如果在事件的范围中,就响应

class TextRenderView: UIView {
let frameRef:CTFrame
let theSize: CGSize
// 事件一
let keyOne = "Willy's Wonderland"
// 事件 2
let keyTwo = "威利的仙境"
let rawTxt: String
let contentPage: NSAttributedString
// 事件的两个范围
let keyRanges: [Range<String.Index>]
override init(frame: CGRect){
rawTxt = "When his car breaks down, a quiet loner (Nic Cage) agrees to clean an abandoned family fun center in exchange for repairs. He soon finds himself waging war against possessed animatronic mascots while trapped inside \(keyOne).\n\n 当他的汽车发生故障时,一个安静的独行侠

本文介绍了如何在 iOS 中使用 Core Text 处理点击指定文字的事件,对比了使用 的实现的缺点,并详细讲解了两种基于 Core Text 的实现方式:一种通过计算点击点在文本中的索引响应事件;另一种通过计算文字中心点和半径来扩大点击热区。提供了相关的 GitHub 代码仓库。
最低0.47元/天 解锁文章
8079

被折叠的 条评论
为什么被折叠?



