You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过NSRange获取UITextField光标前带HTML格式的NSAttributedString?

实现光标位置前带HTML格式的内容截取

核心思路

可以实现:先通过光标位置截取对应的NSAttributedString片段,再将该片段转回HTML格式字符串,而非直接取纯文本。

代码实现

  1. 截取光标前的富文本片段
    基于纯文本字符计数的NSRange,直接从textField的attributedText中截取对应范围的富文本:
let cursorPosition = 18 // 已记录的光标位置
guard let fullAttributedText = textField.attributedText else { return }

// 构造光标前内容的NSRange
let targetRange = NSRange(location: 0, length: cursorPosition)
let attributedSubstring = fullAttributedText.attributedSubstring(from: targetRange)
  1. 将富文本片段转回HTML格式
    利用NSAttributedString的data(from:documentAttributes:)方法,把富文本重新编码为HTML格式的数据,再转成字符串:
do {
    // 将富文本转为HTML数据
    let htmlData = try attributedSubstring.data(
        from: NSRange(location: 0, length: attributedSubstring.length),
        documentAttributes: [.documentType: NSAttributedString.DocumentType.html]
    )
    
    // 转成UTF-8编码的字符串
    if let htmlString = String(data: htmlData, encoding: .utf8) {
        // 此时htmlString包含完整HTML结构,例如:<html><head>...</head><body>This is a <b>bold</b> tex</body></html>
        
        // 提取body内的核心内容(可选,根据需求调整)
        let pattern = "<body>(.*?)</body>"
        if let regex = try? NSRegularExpression(pattern: pattern, options: .dotMatchesLineSeparators),
           let match = regex.firstMatch(in: htmlString, range: NSRange(htmlString.startIndex..., in: htmlString)) {
            let innerHtml = String(htmlString[Range(match.range(at: 1), in: htmlString)!])
            print(innerHtml) // 输出:This is a <b>bold</b> tex
        }
    }
} catch {
    print("富文本转HTML失败:\(error.localizedDescription)")
}

关键说明

  • NSAttributedString的range是基于纯文本字符数计算的,和原HTML标签的数量无关,所以直接用cursorPosition构造range是准确的。
  • 转HTML时,系统会根据富文本的属性(如粗体)自动生成对应的HTML标签,而非输出纯文本,这就能得到你需要的带格式内容。
  • 系统生成的HTML会包含<html>、<body>等外层标签,若只需要核心内容,可通过正则或字符串处理提取body内部的部分。

内容的提问来源于stack exchange,提问作者KANAYO AUGUSTIN UG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 17:10:38