[iOS] 문자열 속성 지정

Han's·2023년 11월 8일
0

TIL

목록 보기
18/20
post-thumbnail

위의 Label처럼 같은 Label에서 글자의 크기가 다르게 속성을 지정하고 싶을 때 NSMutableAttributedString을 사용합니다.

코드

private lazy var dollarLabel: UILabel = {
	let label = UILabel()
	label.textAlignment = .center
	label.textColor = .label
        
	let text = NSMutableAttributedString(
		string: "100 $",
		attributes: [.font: UIFont.systemFont(ofSize: 25, weight: .regular)])
        
	text.addAttributes(
		[.font: UIFont.systemFont(ofSize: 35, weight: .bold)],
		range: NSMakeRange(0, 3))
        
	label.attributedText = text
	return label
}()

코드를 보면 기본적으로

text를 NSMutableAttributedString로 생성한 후 기본적인 attributes을 설정해 준 다음

원하는 부분만큼 range를 잡아서 폰트를 바꿔주는 형태로 만드는 방법으로 속성을 지정할 수 있습니다.

기본 속성을 지정한 후 변경할 부분만큼 지정해 줘서 덮어버린다? 고 생각 하면 편할 것 같습니다.

profile
 iOS Developer

0개의 댓글