한 단어만 적용
struct TextWithColoredSubstring: View {
var originalText: String
var coloredSubstring: String
var body: some View {
if let coloredRange = originalText.range(of: coloredSubstring) {
let beforeRange = originalText[..<coloredRange.lowerBound]
let coloredText = originalText[coloredRange]
let afterRange = originalText[coloredRange.upperBound...]
return Text(beforeRange)
.foregroundColor(.black)
+ Text(coloredText)
.foregroundColor(.pink)
+ Text(afterRange)
.foregroundColor(.black)
} else {
return Text(originalText)
.foregroundColor(.black)
}
}
}
예시
TextWithColoredSubstring(originalText: "Also called First Note or Head Note, it is the first, highly volatile scent you smell when you first spray perfume. You can smell it for about 15 minutes.", coloredSubstring: "15")
.font(.system(size: 30, weight: .medium))
여러 단어 적용
(주의 : 처음 등장하는 단어를 체크하기 때문에 공통된 단어들일지라도 처음 등장한 단어에만 적용됨. 모두 적용하고 싶으면 원하는 단어의 수대로 적용해줘야함)
struct MultiColoredText: View {
var originalText: String
var coloredSubstrings: [(String, Color)]
var body: some View {
var currentIndex = originalText.startIndex
var result: Text = Text("")
for (substring, color) in coloredSubstrings {
if let range = originalText.range(of: substring, range: currentIndex ..< originalText.endIndex) {
let beforeRange = originalText[currentIndex ..< range.lowerBound]
let coloredText = originalText[range]
result = result + Text(beforeRange)
.foregroundColor(.black)
result = result + Text(coloredText)
.foregroundColor(color)
currentIndex = range.upperBound
}
}
let remainingText = originalText[currentIndex...]
result = result + Text(remainingText)
.foregroundColor(.black)
return result
}
}
예시
MultiColoredText(originalText: "Also called First Note or Head Note, it is the first, highly volatile scent you smell when you first spray perfume. You can smell it for about 15 minutes.", coloredSubstrings: [("you", .pink),("you", .yellow), ("15", .green)])
.padding(.bottom, 20)