[swift] SwiftyAttributes를 사용하여 텍스트에 작은 대문자로 변경하는 방법

SwiftyAttributes는 Swift에서 텍스트 스타일링을 쉽게 구현할 수 있는 라이브러리입니다. 이러한 라이브러리를 사용하여 텍스트를 작은 대문자로 변경하는 방법을 알아보겠습니다.

먼저, 프로젝트에 SwiftyAttributes를 추가합니다. 이를 위해 Podfile에 아래의 코드를 추가하고 터미널에서 ‘pod install’ 명령을 실행합니다.

pod 'SwiftyAttributes'

그런 다음, 아래의 코드를 사용하여 텍스트에 작은 대문자 스타일을 적용할 수 있습니다.

import SwiftyAttributes

let text = "Hello, World!"
let lowercaseText = text.lowercased()

let attributedText = NSMutableAttributedString(string: lowercaseText)
attributedText.addAttributes([.kern: 5], range: NSRange(location: 0, length: attributedText.length))

// UIFont.smallCapsTextStyle는 iOS 14부터 지원됩니다.
if #available(iOS 14.0, *) {
    let fontDescriptor = UIFont.systemFont(ofSize: 16, weight: .regular).fontDescriptor.addingAttributes([
        .featureSettings: [
            [
                UIFontDescriptor.FeatureKey.featureIdentifier: kLowerCaseType,
                UIFontDescriptor.FeatureKey.typeIdentifier: kLowerCaseSmallCapsSelector
            ]
        ]
    ])
    let smallCapsFont = UIFont(descriptor: fontDescriptor!, size: 0)
    attributedText.addAttribute(.font, value: smallCapsFont, range: NSRange(location: 0, length: attributedText.length))
} else {
    let smallCapsFont = UIFont.systemFont(ofSize: 16).smallCaps()
    attributedText.addAttribute(.font, value: smallCapsFont, range: NSRange(location: 0, length: attributedText.length))
}

위의 코드에서 lowercased() 메서드를 사용하여 텍스트를 소문자로 변환하고, NSMutableAttributedString를 사용하여 소문자 텍스트에 스타일을 적용합니다. 여기서 .kern 특성을 사용하여 문자 간격을 조정하고 .font 특성을 사용하여 폰트를 설정합니다.

프로젝트에서 SwiftyAttributes를 사용하여 텍스트에 작은 대문자 스타일을 적용할 수 있습니다. 이를 사용하여 원하는 효과를 구현해 보세요.

참고 자료: