[swift] SwiftyAttributes를 사용하여 텍스트에 특정 문자열 바꾸는 방법

SwiftyAttributes는 Swift에서 텍스트에 다양한 속성을 적용할 수 있도록 도와주는 라이브러리입니다. 이 라이브러리를 사용하면 간단하게 텍스트 내의 특정 문자열을 원하는 대체 문자열로 바꿀 수 있습니다.

SwiftyAttributes 설치

SwiftyAttributes는 Swift Package Manager(SPM)을 통해 손쉽게 설치할 수 있습니다. 프로젝트의 Package.swift 파일에 다음과 같이 SwiftyAttributes를 추가하세요.

dependencies: [
    .package(url: "https://github.com/eddiekaiger/SwiftyAttributes.git", from: "4.3.0")
]

그리고 해당 프로젝트에서 SwiftyAttributes를 import 해주세요.

텍스트에 특정 문자열 바꾸기

아래는 SwiftyAttributes를 사용하여 텍스트 내의 특정 문자열을 바꾸는 예제 코드입니다.

import SwiftyAttributes

let originalText = "Hello, World!"
let replacementText = "Swift"

let attributedText = originalText.attributed {
    $0.foregroundColor = .red
    $0.font = .systemFont(ofSize: 17)
}.replacingOccurrences(of: "World", with: replacementText)

// attributedText 사용 예시
textView.attributedText = attributedText

위의 예제에서는 originalText 문자열을 Hello, World!로 초기화하고, replacementText 문자열을 Swift로 초기화합니다. 그리고 attributedText를 생성하고, 여기에서 replacingOccurrences(of:with:) 함수를 통해 특정 문자열인 “World”를 replacementText로 대체합니다. 이후에는 attributedText를 텍스트 뷰에 표시해주면 됩니다.

위의 코드는 “World” 문자열을 대체하는 예제이지만, 원하는 대체 문자열이 있는 경우 해당 문자열을 replacingOccurrences(of:with:) 함수의 첫 번째 인자로 넣어주면 됩니다.

결론

SwiftyAttributes를 사용하면 텍스트에 다양한 속성을 적용하고, 특정 문자열을 원하는 대체 문자열로 바꿀 수 있습니다. 이를 통해 사용자에게 더욱 다양하고 풍부한 텍스트 표현을 제공할 수 있습니다.

참고 자료