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

背景:

一般点击文本中的链接跳转,可以用 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 \(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值