Attributed-Text UILabel样式设置与使用指南

想要让 iOS 的UILabel文本更生动、好看吗?试试NSAttributedStringNSMutableAttributedString吧!这两者能让你给文本加上各种酷炫的样式,比如字体、颜色,甚至阴影、描边啥的。比起单纯的文字显示,它们让 UI 看起来更有层次感,用户体验也能得到提升。

比如你可以用NSAttributedString创建带有属性的文本,设置字体、颜色啥的。看下面的例子:

let text = "Hello, World!"
let attributes: [NSAttributedString.Key: Any] = [
  .font: UIFont.systemFont(ofSize: 24),
  .foregroundColor: UIColor.blue
]
let attributedString = NSAttributedString(string: text, attributes: attributes)

如果想要高亮某些部分,可以用NSMutableAttributedString来动态改变文本样式,比如:

let highlightText = "Swift"
let highlightAttributes: [NSAttributedString.Key: Any] = [
  .font: UIFont.boldSystemFont(ofSize: 18),
  .foregroundColor: UIColor.red
]
let attributedHighlight = NSAttributedString(string: highlightText, attributes: highlightAttributes)

,想要让你的文本更具表现力,NSAttributedString是个不错的选择。你可以为每个文本部分单独设置样式,做出各种漂亮的效果。想让 UI 看起来更炫、更有活力?就用它吧!

zip 文件大小:90.64KB