swift - 在 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
}
}
解决方案
如果这只需要简单的文字样式,那么这里是可能的解决方案。
使用 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)
}
推荐阅读
- php - 控制器端请求中未设置 ApiTestCase 中上传的文件
- node.js - 激活 cors 的 axios 网络错误仍然返回错误
- python-3.x - 我正在为连接编写一个 Django 原始查询,例如: Models.obejcts.raw(query) 返回相同的查询
目的 - angular - Angular & Bootstrap 4 日期输入字段 - 模拟日历中的点击
- sql - MariaDB Connector/J 和 AWS RDS Aurora 出现奇怪的间歇性问题
- kql - Kusto 查询 JSON 数组值
- python - Geopandas 说它已经安装,但是当我尝试导入时,我得到了 OSError
- scikit-learn - 可以在 one-hot 编码的多标签分类上使用 sklearn 的 Bagging Classifier 吗?
- c# - Microsoft.Extensions.* nuget 包的 5.x 版本是否需要 .NET 5.0?
- python - 无法从 spacy.gold 导入 biluo_tags_from_offsets