Thanks for everyone who posted an answer here. By reading all answers, I think the solution depends on your application
Than the @mahan's solution would be the best
Text("**Is this part of the text bold?** Yes, it is.")
E.g. All the text is retrieved from backend or there are some other middle layers between the source: text and destination: view
Inspired by the solution by @dip, I have extension to View
extension View {
func hightlight(
text: String,
textFont: Font,
textColor: Color,
highlight: String,
highlightFont: Font,
highlightColor: Color
) -> AttributedString {
var attrText = AttributedString(text)
attrText.font = textFont
attrText.foregroundColor = textColor
if let range = attrText.range(of: highlight) {
attrText[range].font = highlightFont
attrText[range].foregroundColor = highlightColor
}
return attrText
}
}
Then to use it in this way
Text(hightlight(
text: text,
textFont: .system(size: 18, weight: .regular),
textColor: .green,
highlight: highlightedText,
highlightFont: .system(size: 18, weight: .bold),
highlightColor: .red)
)
Here is the full example and final effect
//
// ContentView.swift
// LearnSwiftUI
//
//
import SwiftUI
struct ContentView: View {
let text = "A very long text and we need to the following text to bold. Is this part in bold? Yes, it is."
let highlightedText = "Is this part in bold?"
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("A very long text and we need to the following text to bold. **Is this part in bold?** Yes, it is.")
Text(hightlight(
text: text,
textFont: .system(size: 18, weight: .regular),
textColor: .green,
highlight: highlightedText,
highlightFont: .system(size: 18, weight: .bold),
highlightColor: .red)
)
}
.padding()
}
}
#Preview {
ContentView()
}
extension View {
func hightlight(
text: String,
textFont: Font,
textColor: Color,
highlight: String,
highlightFont: Font,
highlightColor: Color
) -> AttributedString {
var attrText = AttributedString(text)
attrText.font = textFont
attrText.foregroundColor = textColor
if let range = attrText.range(of: highlight) {
attrText[range].font = highlightFont
attrText[range].foregroundColor = highlightColor
}
return attrText
}
}