[SwiftUI] Text 내부 특정 글자만 색상 적용

임클·2024년 1월 26일
0

Swift

목록 보기
36/37
post-thumbnail
post-custom-banner

한 단어만 적용

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)

profile
iOS를 공부하는 임클입니다.
post-custom-banner

0개의 댓글