Jimmy's iOS
iOS) NSAttributedString 과 NSMutableAttributedString 비교 본문
1. NSAttributedString
- 텍스트 자체에 스타일 (색상, 자간, 행간 등) 을 설정할 수 있는 텍스트 타입이다.
활용 예)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 6
// 텍스트의 속성 설정
let attributes : [NSAttributedString.Key : Any] = [
.font : UIFont.systemFont(ofSize : 20.0, weight : .semibold),
.paragraphStyle : paragraphStyle,
.foregroundColor : UIColor.systemPink
]
// 내가 원하는 text 생성후
let text = NSAttributedString(string : "안녕하세요 하하하 테스트입니다.", attributes : attributes)
// textView의 attributedText 에 대입
textView.attributedText = text
2. NSMutableAttributedString
- NSAttributedString 의 특정 범위 NSRange 에 다양한 스타일 (색상, 자간, 행간 등) 을 설정할 수 있는 텍스트 타입이다.
활용 예)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 6
// 텍스트의 속성 설정
let attributes : [NSAttributedString.Key : Any] = [
.font : UIFont.systemFont(ofSize : 20.0, weight : .semibold),
.paragraphStyle : paragraphStyle,
.foregroundColor : UIColor.systemPink
]
// 내가 원하는 text 생성후
let text = NSMutableAttributedString(string : "안녕하세요 하하하 테스트입니다.", attributes : attributes)
// 내가 중간에 바꾸고 싶은 속성 생성
let additionalAttributes : [NSAttributedString.Key : Any] = [
.font : UIFont.systemFont(ofSize : 20.0, weight : .semibold),
.paragraphStyle : paragraphStyle,
.foregroundColor : UIColor.systemRed
]
// range 범위만큼 설정한 속성을 추가
text.addAttributes(additionalAttributes, range : NSRange(location: 2, length : 10))
// textView의 attributedText 에 대입
textView.attributedText = text
'iOS' 카테고리의 다른 글
iOS) Coursel CollectionView 코드로 구현해보기 (0) | 2022.03.18 |
---|---|
iOS) Localization 알아보기 (0) | 2022.02.23 |
iOS) UIStackView 를 이용하여 스크롤 뷰 만들기 (0) | 2021.12.21 |
iOS) 앱 특정 화면에서만 가로(세로) 모드 지원하기 (0) | 2021.12.16 |
iOS) 아이폰 화면 자동 잠금 방지 (슬립 모드 방지) (0) | 2021.12.14 |