Core Text 处理点击指定文字的事件

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景:

一般点击文本中的链接跳转,可以用 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 \(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值