[swift] SwiftyAttributes를 사용하여 텍스트에 특정 부분을 강조하는 방법

소개

SwiftyAttributes는 Swift에서 NSAttributedString을 쉽게 생성하고 편집할 수 있는 라이브러리입니다. 텍스트에 특정 부분을 강조하거나 스타일을 적용할 때 유용하게 사용할 수 있습니다.

설치

SwiftyAttributes를 사용하기 위해 프로젝트에 CocoaPods를 사용하는 경우, Podfile에 다음을 추가합니다:

pod 'SwiftyAttributes'

그리고 터미널에서 다음 명령어를 실행합니다.

pod install

사용 방법

  1. SwiftyAttributes를 import 합니다.
import SwiftyAttributes
  1. NSAttributedString을 생성합니다.
let attributedString = "Hello, World!".withAttributes([
    .foregroundColor(.red),
    .font(.systemFont(ofSize: 20)),
])
  1. 텍스트의 일부를 강조하거나 스타일을 적용합니다.
let attributedString = "Hello, World!".withAttributes([
    .foregroundColor(.red),
    .font(.systemFont(ofSize: 20)),
    .underlineStyle(.single),
    .underlineColor(.blue),
]).styled(with: [
    .foregroundColor(.blue),
    .font(.boldSystemFont(ofSize: 24)),
], range: NSRange(location: 0, length: 5))

위의 코드에서 styled(with:range:) 메서드를 사용하여 텍스트의 일부에 새로운 스타일을 적용합니다. range 매개변수는 적용할 텍스트의 범위를 나타냅니다.

  1. NSAttributedString을 UILabel, UITextView 등과 같이 텍스트를 표시하는 컨트롤에 적용합니다.
label.attributedText = attributedString

결론

SwiftyAttributes를 사용하면 Swift로 쉽게 NSAttributedString을 생성하고 편집할 수 있습니다. 텍스트에 특정 부분을 강조하거나 다양한 스타일을 적용하는 데 유용합니다.

참고 자료