背景:
一般点击文本中的链接跳转,可以用 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 \(