NSMutableAttributedString - Label 글자 속성 변경

hoBahk·2022년 2월 10일
0
post-thumbnail

안녕하세요.
오늘은 label 글자 속성을 변경하는 방법에 대해서 알아보겠습니다.

NSMutableAttributedString를 이용하여 글자의 속성을 변경할 수 있습니다.

예제를 보시면 이해하실 수 있습니다.

가운데 줄긋기

let text = "Hello, Swift"
let attributeString = NSMutableAttributedString(string: text)
attributeString.addAttribute(
    NSAttributedString.Key.strikethroughStyle,
    value: NSUnderlineStyle.single.rawValue,
    range: (text as NSString).range(of: "Swift")
)
label.attributedText = attributeString

색상 변경

let text = "Hello, Swift"
let attributeString = NSMutableAttributedString(string: text)
attributeString.addAttribute(
    .foregroundColor,
    value: UIColor.red,
    range: (text as NSString).range(of: "Swift")
)
label.attributedText = attributeString

크기변경 및 볼드체

let text = "Hello, Swift"
let fontSize = UIFont.boldSystemFont(ofSize: 60)
let attributeString = NSMutableAttributedString(string: text)
attributeString.addAttribute(
    .font,
    value: fontSize,
    range: (text as NSString).range(of: "Swift")
)
label.attributedText = attributeString

밑줄 긋기, 밑줄 색 정하기

let text = "Hello, Swift"
let attributeString = NSMutableAttributedString(string: text)
attributeString.addAttribute(
    .underlineStyle,
    value: NSUnderlineStyle.thick.rawValue,
    range: (text as NSString).range(of: "Swift")
)
attributeString.addAttribute(
    .underlineColor,
    value: UIColor.red,
    range: (text as NSString).range(of: "Swift"))
label.attributedText = attributeString

배경색 지정

let text = "Hello, Swift"
let attributeString = NSMutableAttributedString(string: text)
attributeString.addAttribute(
    .backgroundColor,
    value: UIColor.yellow,
    range: (text as NSString).range(of: "Swift"))
label.attributedText = attributeString

해당 글자 높이? 변경

let text = "Hello, Swift"
let attributeString = NSMutableAttributedString(string: text)
attributeString.addAttribute(
    .baselineOffset,
    value: 5,
    range: (text as NSString).range(of: "Swift"))
label.attributedText = attributeString

감사합니다.

profile
호박에 줄 그어서 수박 되는 성장 드라마

0개의 댓글