Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- swift documentation
- Protocol
- 리펙토링
- map
- ios
- swiftUI
- Observable
- collectionview
- Xcode
- combine
- Refactoring
- 애니메이션
- clean architecture
- UITextView
- Human interface guide
- RxCocoa
- SWIFT
- rxswift
- tableView
- 스위프트
- 리펙터링
- uitableview
- uiscrollview
- HIG
- UICollectionView
- 리팩토링
- ribs
- 클린 코드
- MVVM
- Clean Code
Archives
- Today
- Total
김종권의 iOS 앱 개발 알아가기
[iOS - swift] NSAttributedString vs AttributedString 개념 본문
NSAttributedString와 AttributedString 비교
- NSAttributedString은 iOS 3.2부터 사용이 가능하며 String에 색상, 하이퍼링크, accessibility 관련 속성을 같이 가지고 있는 데이터 타입
- AttributedString은 iOS 15부터 사용이 가능하며 NSAttributedString을 보완한 형태
- SwiftUI에서 Text(attributedString)과 같이 바로 사용이 가능
비교하며 AttributedString 알아보기
- 프로퍼티 입력
- NSAttributedString은 attributes를 dictionary 형태로 Key-value로 입력하는 형태
- AttributedString은 AttributedString 타입 자체의 프로퍼티에 입력이 가능
- (AttributedString가 직관적으로 사용하는 형태이고 개발자가 attributedString.만 입력해도 어떤 프로퍼티가 있는지 쉽게 파악이 가능)
// NSAttributedString
private var nsAttributedString: NSAttributedString {
let string = "NSAttributedString String"
let attributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.foregroundColor: UIColor.systemPink,
NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 40),
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue
]
return NSAttributedString(string: string, attributes: attributes)
}
// AttributedString
private var attributedString: AttributedString {
let string = "Attributed String"
var attributedString = AttributedString(string)
attributedString.foregroundColor = .blue
attributedString.font = .boldSystemFont(ofSize: 40)
attributedString.underlineStyle = .single
return attributedString
}
- 변환
- 서로 변경이 가능 NSAttributedString <-> AttributedString
let attributedString2 = AttributedString(nsAttributedString)
let nsAttributedString2 = NSAttributedString(attributedString)
- 확장성
- AttributedString은 직관적으로 '+'를 사용하여 일반 문자열 다루듯이 결합이 가능
let attributedString2 = AttributedString(nsAttributedString)
label.attributedText = NSAttributedString(attributedString + attributedString2)
정리
- NSAttributedString은 예전 iOS 3.2 부터 사용
- AttributedString은 NSAttributedString을 더욱 보완하여 탄생했으며 iOS 15부터 사용 가능
- SwiftUI에서 바로 사용 가능
- property를 변경하며 속성 변경이 가능하여 직관적으로 사용이 가능
- 일반 문자열 처럼 '+'로 attributedString 결합이 가능
- NSAttributedString으로도 변환이 쉽게 가능
- iOS 15 이상 버전 target으로 개발한다면 NSAttributedString말고 AttributedString 사용을 지향
* 참고
https://developer.apple.com/documentation/foundation/attributedstring
https://sarunw.com/posts/attributed-string/
https://developer.apple.com/documentation/foundation/nsattributedstring
'iOS 응용 (swift)' 카테고리의 다른 글
Comments