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

SwiftUI中Text拼接超限崩溃问题求解决方案

解决SwiftUI中长文本搜索高亮崩溃的问题

你遇到的EXC_BAD_ACCESS崩溃,根源确实不是字符串长度,而是Text实例的链式拼接次数过多。SwiftUI的Text是值类型,每次用+拼接都会生成新的Text实例,当你处理几千个单词的文本时,这种嵌套拼接会让Text的结构变得异常复杂,最终触发内存访问错误。

替代方案:用AttributedString实现高效高亮

相比逐词拼接Text,AttributedString是更适合处理富文本的方案——它可以一次性给整个字符串的指定范围设置样式,不会生成大量嵌套的Text实例,完美解决拼接次数超限的问题。

修改后的核心代码如下:

// 调用高亮文本
highlightedText(str: self.recipes.last!.recipeData!)
    .multilineTextAlignment(.leading)

// 基于AttributedString的高亮实现
func highlightedText(str: String) -> Text {
    let searchTerm = searched.uppercased()
    var attributedStr = AttributedString(str)
    let baseFont = Font.system(size: CGFloat(settings.fontSize))
    
    // 循环查找所有匹配的文本范围,设置高亮样式
    var currentSearchRange = attributedStr.startIndex..<attributedStr.endIndex
    while let matchRange = attributedStr.range(of: searchTerm, options: .caseInsensitive, range: currentSearchRange) {
        attributedStr[matchRange].font = baseFont.bold()
        attributedStr[matchRange].foregroundColor = .yellow
        // 更新搜索范围,避免重复匹配同一内容
        currentSearchRange = matchRange.upperBound..<attributedStr.endIndex
    }
    
    // 给整个文本设置基础字体,确保未高亮部分样式统一
    attributedStr.font = baseFont
    
    return Text(attributedStr)
}

为什么这个方案更靠谱?

  1. 性能更优:不管文本有多长,只会生成一个Text实例,不会有嵌套拼接带来的内存负担;
  2. 支持多词搜索:原来按空格拆分单词的方式,会把多词搜索词拆碎,而AttributedString可以正确匹配连续的多词内容;
  3. 样式统一:可以一次性给整个文本设置基础字体,避免手动拼接空格时可能出现的样式不一致问题;
  4. 扩展性强:如果后续需要支持正则匹配、部分词匹配等复杂需求,只需要调整范围查找的逻辑即可。

内容的提问来源于stack exchange,提问作者JerseyDevel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 16:02:45