안녕하세요.
오늘은 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
감사합니다.