텍스트 자체에 스타일을 설정할 수 있는 텍스트 타입
일반적으로 UI Component의 텍스트의 속성은
UI Component의 스타일을 따른다.
예를 들어 textView에 작성되는 텍스트는
textView.font = .systemfont( ~~)
다음과 같이 textView자체에 지정된 폰트 스타일을 따르게 된다.
그러나 이렇게 UI componet의 스타일을 따르지 않고
텍스트(string) 자체에 스타일을 지정하고자 할 때 NSAttributedString을 사용한다.
let attributes : [NSAttributedString.key: Any] = []
let attributes : [NSAttributedString.key] = [
.font: UIFont.systemFont(ofSize: 20.0, weight: .semibold),
.foregroundColor: UIColor.systemBlue,
.paragraphStyle: paragraphStyle,
.backgroundColor: UIColor.lightGray,
.underlineStyle: NSNumber(value: 1),
.textEffect: NSAttributedString.TextEffectStyle.letterpressStyle
]
으로 설정하고
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 10.0
문단 스타일은 다음과 같이 NSMutableParagraphStyle() 객체로
따로 설정해주어야 한다.
let text = NSAttributedString(string: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.", attributes: attributes)
textView.attributedText = text
다음과 같이 텍스트에 속성이 설정이 된다.
NSAttributedString의 특정 범위에 다양한 스타일(색상,자간, 행간 등)을 설정할 수 있는 텍스트 타입
NSAttributedString 을 사용할 때와 똑같지만 특정 범위에 적용할 추가 attribute를 생성해주어야한다는 차이가 있다.
let attributes : [NSAttributedString.key] = [
.font: UIFont.systemFont(ofSize: 20.0, weight: .semibold),
.foregroundColor: UIColor.systemBlue,
.paragraphStyle: paragraphStyle,
.backgroundColor: UIColor.lightGray,
.underlineStyle: NSNumber(value: 1),
.textEffect: NSAttributedString.TextEffectStyle.letterpressStyle
]
let additionalAttributes : [NSMutableAttributedString.Key: Any] = [
.foregroundColor: UIColor.systemRed,
.font: UIFont.systemFont(ofSize: 30.0, weight: .thin)
]
let text = NSMutableAttributedString(string: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.", attributes: attributes)
text.addAttributes(additionalAttributes, range: NSRange(location: 5, length: 27) )
textView.attributedText = text