swift富⽂本开发之SwiftyAttributes
对于开发中使⽤富⽂本的情况是⾮常常见的⼀个场景,⽽且swift已经有⼀个很好的⽀持富⽂本的NSAttributedString。但是使⽤起来还是有点⿇烦,不太⽅便。⽹上也有⼀个第三⽅的框架SwiftyAttributes,试⽤起来很好⽤。然后这个功能⾮常的棒,⽀持的平台也⽐较多,如果我们只需要⼿机平台的话,那么我们⽤上它就有点不太值了。但是我们可以根据他的思路单独封装⼀个专⽤的⼿机平台sdk。
这个源码核⼼的实现相对⽐较简单,但是⾥⾯的思想确实很新颖,也只有swift能这么实现了,那么我们可以按照他的逻辑来实现。
⾸先我们需要定义⼀个AttributeNameKey枚举类型:
enum AttributeNameKey {
ca font(UIFont)
ca textColor(UIColor)
ca paragraphStyle(NSParagraphStyle)
var keyName: NSAttributedString.Key {
let name: NSAttributedString.Key
switch lf {
ca .textColor:
name = .foregroundColor
ca .paragraphStyle:
name = .paragraphStyle
ca .font:
name = .font
}
return name;
双肺间质性改变}
var value: Any {
switch lf {
ca .font(let font):
return font;
ca .textColor(let color):
return color;医疗九不准
ca .paragraphStyle(let style):
return style;
}
}
}
这个主要完成了两个功能,对应着NSAttributedString的键值。这⾥也⽤到了swift独有的值绑定特性。
接下来我们扩展NSAttributedString的使⽤。
extension NSAttributedString {
func withAttributes(nameKey:[AttributeNameKey]) -> NSMutableAttributedString {
let mutable = mutableCopy() as! NSMutableAttributedString;
for item in nameKey {
mutable.addAttributes([item.keyName:item.value], range: .init(location: 0, length: length));
}
return mutable;
}
func withAttribute(nameKey: AttributeNameKey) -> NSMutableAttributedString {
withAttributes(nameKey: [nameKey])
}
磕头拜年}
这个是给NSAttributedString添加了两个属性,这个是核⼼,我们也可以再添加具体的函数⽐如像下⾯的⼀样:
func withFont(font: UIFont) -> NSMutableAttributedString {切线是什么意思
withAttribute(nameKey: .font(font))
}
为了给字符串直接加上富⽂本属性还需要给String也添加⼀个扩展:
extension String {
var attributed: NSMutableAttributedString {
NSMutableAttributedString(string: lf)
}
func withAttribute(nameKey: AttributeNameKey) -> NSMutableAttributedString {
attributed.withAttributes(nameKey: [nameKey]);
}
func withAttributes(nameKey:[AttributeNameKey]) -> NSMutableAttributedString {
attributed.withAttributes(nameKey: nameKey)
}
}
为了能让NSAttributedString实现像swift字符串⼀样的加号操作,我们需要给NSAttributedString添加⼀个加号操作符。如下:
extension NSAttributedString {
static func + (left: NSAttributedString,right: NSAttributedString) -> NSAttributedString {
let compone = left as! NSMutableAttributedString;
活字印刷是谁发明的compone.append(right);
return compone;
一岁宝宝辅食食谱大全}
}
放大镜快捷键这样我们就可以开⼼的像字符串⼀样的使⽤了。具体使⽤如下:
func testAttribute() {
let text = "⾯条".withAttribute(nameKey:
.font(UIFont.systemFont(ofSize: 15))).withAttribute(nameKey:
.d)) + "(12元)".withAttribute(nameKey:
.
font(UIFont.systemFont(ofSize: 12))).withAttribute(nameKey:
.));
}
如果细⼼的⼈会发现,属性太少不够⽤,这⾥我先申明⼀下,这个只是⼀个思路,也是⼀个例⼦,我们可以添加NSAttributedString所有的属性。当然最好⽤到那个添加那个,没有必要全部添加上。
其实还有个⼩问题,如果要添加图⽚还是有点⿇烦。那么我们也封装⼀下图⽚。如下:
蔬菜单词extension UIImage {
func attribute(bounds: CGRect) -> NSMutableAttributedString {
let imageText = NSTextAttachment();
imageText.image = lf
imageText.bounds = bounds;
return NSMutableAttributedString(attachment: imageText)
}
}
这样我们就可以直接按照字符串的规则添加图⽚了。⾮常⽅便。
好了对于这个功能就先到这⾥了,成功的路上总不缺少努⼒的⼈,加油。。。。。