swift——富文本文字的简单使用

如果需要一个字符前后文字颜色不一样,也就是说一个字符串分成多个部分,每个部分的属性(颜色,字体,大小等)不一样,那就是富文本文字 NSMutableAttributedString

直接上代码了

let str = "今宵杯中映着明月 物华天宝人杰地灵"       
let attrStr = NSMutableAttributedString.init(string: str)
attrStr.addAttribute(NSAttributedStringKey.foregroundColor, value:UIColor.orange, range:NSRange.init(location:0, length: 8))
attrStr.addAttribute(NSAttributedStringKey.foregroundColor, value:UIColor.red, range:NSRange.init(location:9, length: 8))
label1.attributedText = attrStr

/// 仅字体和大小       
label2.attributedText = NSAttributedString.init(string:"这是一串文字", attributes: [NSAttributedStringKey.backgroundColor:UIColor.cyan,  NSAttributedStringKey.font:UIFont.systemFont(ofSize:28)])

/// 背景色       
label3.attributedText = NSAttributedString.init(string:"这是一个有背景色的文字", attributes: [NSAttributedStringKey.backgroundColor:UIColor.green,  NSAttributedStringKey.font:UIFont.systemFont(ofSize:18)])

/// 阴影       
let shadow = NSShadow.init()       
shadow.shadowColor = UIColor.red       
shadow.shadowOffset = CGSize.init(width: 2, height: 2)       

label4.attributedText = NSAttributedString.init(string:"这是一个有阴影的文字", attributes: [NSAttributedStringKey.foregroundColor:UIColor.red,  NSAttributedStringKey.font:UIFont.systemFont(ofSize:18), NSAttributedStringKey.shadow: shadow])

/// 下划线       
label5.attributedText = NSAttributedString.init(string:"这是一个有下划线的文字", attributes: [NSAttributedStringKey.foregroundColor:UIColor.purple,  NSAttributedStringKey.font:UIFont.systemFont(ofSize:18), NSAttributedStringKey.underlineStyle:NSUnderlineStyle.styleSingle.rawValue])
复制代码
效果图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值