首页 > 解决方案 > 在 SwiftUI 中突出显示文本的特定部分

问题描述

您好,我是 Swift 新手,我在项目中使用 SwiftUI,我下载了一些天气数据并将其显示在 ContentView() 中。

如果文本的某些部分包含某些特定单词,我想突出显示它,但我不知道如何开始。

在 ContentView() 中,我尝试设置一个函数接收从 web 下载的字符串并返回一个字符串。我认为这是错误的,因为 SwiftUI 根本没有为 Text 应用修饰符。

例如,在我的 ContentView() 中,我希望单词 Thunderstorm 具有 .bold() 修饰符:

struct ContentView: View {
  let testo : String = "There is a thunderstorm in the area"

  var body: some View {
    Text(highlight(str: testo))
  }

  func highlight(str: String) -> String {
    let textToSearch = "thunderstorm"
    var result = ""

    if str.contains(textToSearch) {
      let index = str.startIndex
      result = String( str[index])
    }

    return result
  }

}

标签: swiftstringsearchtextswiftui

解决方案


如果这只需要简单的文字样式,那么这里是可能的解决方案。

使用 Xcode 11.4 / iOS 13.4 测试

演示

struct ContentView: View {
    let testo : String = "There is a thunderstorm in the area. Added some testing long text to demo that wrapping works correctly!"


    var body: some View {
        hilightedText(str: testo, searched: "thunderstorm")
            .multilineTextAlignment(.leading)
    }

    func hilightedText(str: String, searched: String) -> Text {
        guard !str.isEmpty && !searched.isEmpty else { return Text(str) }

        var result: Text!
        let parts = str.components(separatedBy: searched)
        for i in parts.indices {
            result = (result == nil ? Text(parts[i]) : result + Text(parts[i]))
            if i != parts.count - 1 {
                result = result + Text(searched).bold()
            }
        }
        return result ?? Text(str)
    }
}

注意:下面是以前使用过的函数,但正如@Lkabo所评论的,它对非常长的字符串有限制

func hilightedText(str: String) -> Text {
    let textToSearch = "thunderstorm"
    var result: Text!

    for word in str.split(separator: " ") {
        var text = Text(word)
        if word == textToSearch {
            text = text.bold()
        }
        result = (result == nil ? text : result + Text(" ") + text)
    }
    return result ?? Text(str)
}

推荐阅读