var str:String = "When I was ###young$$$, I thought ###time$$$ was money" VStsck{ Text(str) } enter image description here
Asked
Active
Viewed 540 times
-1
-
1Does this answer your question https://stackoverflow.com/a/61671431/12299030? Or this one https://stackoverflow.com/a/59531328/12299030? – Asperi Aug 23 '21 at 07:52
-
thanks for answer , I know to use Text()+Text(), but my string is a variable, I only know that the characters that need to be highlighted are contained in ###$$$, and i use ios 14 swift5 – tom Aug 23 '21 at 08:11
-
Then you just need to parse it and combine result as in https://stackoverflow.com/a/62111947/12299030 – Asperi Aug 23 '21 at 08:41
2 Answers
1
You can parse your string using regular expression and build Text
based on found ranges:
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
}
}
Usage:
HighlightedText("When I was ###young$$$, I thought ###time$$$ was money")

Phil Dukhov
- 67,741
- 15
- 184
- 220
0
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)
}
}

tom
- 3
- 1