Jimmy's iOS

iOS) NSAttributedString 과 NSMutableAttributedString 비교 본문

iOS

iOS) NSAttributedString 과 NSMutableAttributedString 비교

Jimmy Youn 2022. 2. 21. 00:38

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