[Swift] UILabel에서 attributedText를 활용한 들여쓰기와 내어쓰기

2021. 4. 8. 15:14iOS/Swift

 

안내사항 문구를 만들다가 글자 들여쓰기 어떻게 하지..? 

dot 라벨 만들고,, 라벨 만들어야하나...? 이런 생각을 했었다.

 

다음 웹툰 캐시 구매 유의사항 문구

하지만 attributedText를 통해서 만들 수 있지않을까? 하고 구글링하고 정리 겸 블로그 글을 쓰게 되었다. (의식의 흐름)

 

 

어트리뷰트 인스펙터에서도 설정 가능!

인스펙터에서도 설정이 가능하지만 요상하게도 적용이 안되서 코드로 설정했다.

 

들여쓰기, 내어쓰기는 NSMutableParagraphStyle()를 통해 설정할 수 있다.

 

테스트 결과물

 

zeroLabel.text = testString

let firstParagraphStyle = NSMutableParagraphStyle()
firstParagraphStyle.headIndent = 10
firstLabel.attributedText = NSAttributedString(string: testString, attributes: [NSAttributedString.Key.paragraphStyle: firstParagraphStyle])
        
let secondParagraphStyle = NSMutableParagraphStyle()
secondParagraphStyle.firstLineHeadIndent = 10
secondLabel.attributedText = NSAttributedString(string: testString, attributes: [NSAttributedString.Key.paragraphStyle: secondParagraphStyle])
        
let thirdParagraphStyle = NSMutableParagraphStyle()
thirdParagraphStyle.firstLineHeadIndent = 0
thirdParagraphStyle.headIndent = 10
thirdLabel.attributedText = NSAttributedString(string: testString, attributes: [NSAttributedString.Key.paragraphStyle: thirdParagraphStyle])

 

참고로 NSParagraphStyle()은 get-only 함수임👀

third Label은 구글링하다가 저렇게 적혀있길래 뭐가 다른가 싶어서 해봤는데 잘 모르겠다;