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])

代码图:

代码图

效果图:

效果图

转载请注明出处,谢谢。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容