swift3.0 我们进行NSAttributedString富文本的操作的时候一般是这样写的attributeString.addAttribute()
let sendTextStr = "发送好友(消息将发送以下人员)"
var zonerange = NSRange()
zonerange = (sendTextStr as NSString).range(of: "(")
//富文本设置
let attributeString = NSMutableAttributedString(string:sendTextStr)
//设置字体大小
attributeString.addAttribute(NSFontAttributeName,
value: UIFont.systemFont(ofSize: 16),
range: NSMakeRange(0,zonerange.location))
attributeString.addAttribute(NSFontAttributeName,
value: UIFont.systemFont(ofSize: 12),
range: NSMakeRange(zonerange.location, (sendTextStr as NSString).length-zonerange.location))
//设置字体颜色
attributeString.addAttribute(NSForegroundColorAttributeName, value: Common.transferStringToColor(colorStr: "555555"),
range: NSMakeRange(0, zonerange.location))
attributeString.addAttribute(NSForegroundColorAttributeName, value: Common.transferStringToColor(colorStr: "cccccc"),
range: NSMakeRange(zonerange.location, (sendTextStr as NSString).length-zonerange.location))
//设置文字背景颜色
// attributeString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.green,
// range: NSMakeRange(3,3))
sendText.attributedText = attributeString
而今天给大家介绍一个库SwiftyAttributes库,他的写法我觉得更好一点,GitHub:https://github.com/eddiekaiger/SwiftyAttributes
e.g.1.0:设置字体颜色
attributeString.withTextColor( Common.transferStringToColor(colorStr: "555555"))
e.g.1.1 在某个区间内设置颜色
attributeString.addAttributes([.textColor(.red)], range: 0..<5)
e.g.1.2 设置文字背景颜色
"attributeString".withBackgroundColor(.red),
e.g.1.3 设置文字间距
"attributeString".withKern(5.1),
e.g.1.4 一段文字中有图片(重点介绍的一个)采用的是他demo上的一个案例 TextAttachment -> NSTextAttachment 设置这个的bounds可以设置图片的大小
{
let attachment = TextAttachment()
attachment.bounds = CGRect(x: 0, y: 0, width: 5, height: 5)
attachment.image = UIImage(named: "Star")
let str = "Attachment With Image".attributedString
str.replaceCharacters(in: 10 ..< 12, with: NSAttributedString(attachment: attachment))
return str
}(),
更多的属性我就不一一介绍了(跟NSAttributedString时一样的)如:underlineStyle下划线 shadow阴影 TextEffect文字效果 等,具体的可以去GitHub上看
下面关于他的写法介绍
e.g.1 {}
{
attributeString.addAttributes([.underlineStyle(.styleDouble), .textColor(.blue)], range: 3 ..< 8)
attributeString.addAttributes([.strikethroughStyle(.styleThick), .strikethroughColor(.red)], range: 16 ..< 22)
attributeString.addAttributes([.textColor(.red)], range: 22..<24)
attributeString.addAttributes([.textColor(.red)], range: 0..<5)
return attributeString
}()
e.g.2 .withAttribute 单个属性
let str = "QWEWSSDS".withAttribute(<#T##attribute: Attribute##Attribute#>)
e.g.3 .withAttributes 多个属性
let str = "aADADASDADADS".withAttributes(<#T##attributes: [Attribute]##[Attribute]#>)
e.g.4 也可以一直 .with 连下去(这个可以用来对整体字符串的修改)
"UnderliAD阿萨达的啊大大".withUnderlineColor(.red).withUnderlineStyle(.styleDouble),
关于SwiftyAttributes我就简单的介绍到这了