개발콩블로그

[iOS] UILabel에서 특정 텍스트 변경하기 (NSMutableAttributedString) 본문

iOS

[iOS] UILabel에서 특정 텍스트 변경하기 (NSMutableAttributedString)

devBean 2025. 2. 16. 19:08

안녕하세요!

개발콩입니다. 오늘은 UILabel에서 특정 텍스트 변경하는 방법 대해서 소개하도록 하겠습니다.

 

 

어떤 상황에 필요할까?

우리는 주로 사용자에게 UILabel에서 특정 text를 Bold처리 혹은 Highlight를 함으로써 많은 이점을 얻을 수 있습니다.

  • 가독성 향상 - 중요한 정보가 한눈에 들어온다
  • 빠른 정보 전달 - 시선을 끌어서 사용자에게 먼저 정보를 제공할 수 있다.

이러한 UX적인 측면 향상을 위해서 많이 사용할 수 있는 방법인 것 같습니다.

 

 

 

NSMutableAttributedString

텍스트 일부에 대해 시각적 스타일, 하이퍼링크, 접근성 데이터 등의 속성을 변경할 수 있는 가변 문자열입니다.

 

 

사용방법

guard let labelText = (UILabel).text else { return }
let attributedString = NSMutableAttributedString(string: labelText)

먼저 UILabel의 text를 이용해서 가변 문자열 attributedString을 만듭니다.

 

 

 

for text in texts {
    guard let range = labelText.range(of: text, options: .caseInsensitive) else { return }
    let nsRange = NSRange(range, in: labelText)
    attributedString.addAttribute(.foregroundColor, value: color, range: nsRange)
}

변경하고 싶은 text를 순회하며 UILabel에서 변경하고 싶은 text의 범위를 구합니다.

.caseInsensitive 옵션을 사용하여 대소문자 구문 없이 찾을 수 있도록 합니다.

이후, 만들었던 가변 문자열 attributedString에 찾은 범위에 원하는 속성을 추가합니다.

 

 

(UILabel).attributedText = attributedString

UILabel의 attributeText에 우리가 만들었던 attributedString을 넣어줍니다.

 

 

 

전체 코드

extension UILabel {
    func highlightText(for texts: String..., with color: UIColor) {
        guard let labelText = self.text else { return }
        let attributedString = NSMutableAttributedString(string: labelText)
        
        for text in texts {
            guard let range = labelText.range(of: text, options: .caseInsensitive) else { return }
            let nsRange = NSRange(range, in: labelText)
            attributedString.addAttribute(.foregroundColor, value: color, range: nsRange)
        }
        
        self.attributedText = attributedString
    }
}

 

UILabel의 원하는 text에 highlight를 할 수 있는 메서드입니다.

 

 

extension UILabel {
    
    func boldText(for texts: String...) {
        guard let labelText = self.text else { return }
        let attributedString = NSMutableAttributedString(string: labelText)
        let fontSize = self.font.pointSize
        
        for text in texts {
            guard let range = labelText.range(of: text, options: .caseInsensitive) else { return }
            let nsRange = NSRange(range, in: labelText)
            attributedString.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: fontSize), range: nsRange)
        }
        
        self.attributedText = attributedString
    }
}

 

UILabel의 원하는 text에 Bold처리를 할 수 있는 메서드입니다.

 

 

 

사용화면