如何使用 swift ui 显示突出显示的单词
Posted
技术标签:
【中文标题】如何使用 swift ui 显示突出显示的单词【英文标题】:How to display highlighted words using swift ui 【发布时间】:2021-08-23 07:47:04 【问题描述】:var str:String = "当我 ###young$$$ 的时候,我认为 ###time$$$ 就是金钱" VStsck 文本(字符串) enter image description here
【问题讨论】:
这是否回答了您的问题***.com/a/61671431/12299030?还是这个***.com/a/59531328/12299030? 感谢回答,我知道用Text()+Text(),但是我的字符串是变量,我只知道###$$里面包含了需要高亮的字符$,我使用 ios 14 swift5 然后你只需要像***.com/a/62111947/12299030一样解析它并组合结果 【参考方案1】:您可以使用正则表达式解析字符串并根据找到的范围构建Text
:
struct HighlightedText: View
let text: Text
private static let regularExpression = try! NSRegularExpression(
pattern: "###(?<content>((?!\\$\\$\\$).)*)\\$\\$\\$"
)
private struct SubstringRange
let content: NSRange
let full: NSRange
init(_ string: String)
let ranges = Self.regularExpression
.matches(
in: string,
options: [],
range: NSRange(location: 0, length: string.count)
)
.map match in
SubstringRange(
content: match.range(withName: "content"),
full: match.range(at: 0)
)
var nextNotProcessedSymbol = 0
var text = Text("")
let nsString = string as NSString
func appendSubstringStartingNextIfNeeded(until endLocation: Int)
if nextNotProcessedSymbol < endLocation
text = text + Text(nsString.substring(
with: NSRange(
location: nextNotProcessedSymbol,
length: endLocation - nextNotProcessedSymbol
)
))
for range in ranges
appendSubstringStartingNextIfNeeded(until: range.full.location)
text = text + Text(nsString.substring(with: range.content))
.foregroundColor(Color.red)
nextNotProcessedSymbol = range.full.upperBound
appendSubstringStartingNextIfNeeded(until: string.count)
self.text = text
var body: some View
text
用法:
HighlightedText("When I was ###young$$$, I thought ###time$$$ was money")
【讨论】:
【参考方案2】:func hilightText(str:String) -> Text
var resultText:Text = Text("")
if(str.contains("###"))
let titleArr:Array<String> = str.components(spearatedBy:"###")
for(title in titleArr)
resultText = resultText
+ Text(title.components(spearatedBy:"$$$")[0]).foregroundColor(Color.red)
+ Text(title.components(spearatedBy:"$$$")[1]).foregroundColor(Color.gray)
else
resultText = resultText + Text(title).foregroundColor(Color.gray)
return resultText
else
return Text(str).foregroundColor(Color.gray)
struct View1:View
@State var title = "When I was ###young$$$, I thought ###time$$$ was money"
var body : some View
hilightText(str:title)
【讨论】:
我找到了一个简单的解决方案,虽然看起来并不优雅以上是关于如何使用 swift ui 显示突出显示的单词的主要内容,如果未能解决你的问题,请参考以下文章