swift - 在 SwiftUI 中突出显示文本的特定部分

标签 swift string search text swiftui

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

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

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

例如,在我的 ContentView() 中,我希望雷暴这个词具有 .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
  }

}

最佳答案

如果那只需要简单的文字样式,那么这里是可能的解决方案。
使用 Xcode 11.4/iOS 13.4 测试
demo

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)
}

关于swift - 在 SwiftUI 中突出显示文本的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62111551/

相关文章:

java - 布局放置不正确? (还是不行)

android - 关于 Android 公钥的说明?

ruby-on-rails - Ruby on Rails : How to set up "find" options in order to not use cache

arrays - 查找在线性时间内出现超过 n/4 次的所有元素

swift 4 将图像文字添加到字符串

swift - UIApplication.shared.open 在 ios 13 中不起作用

swift - 拒绝从类内部但函数内部的任何地方编辑属性

string - 使用索引比较 Rust 字符串中的字符

正则表达式浏览器搜索?

ios - 上传图像/视频到 FTP Swift 3.0