测试已测试 | ✗ |
语言语言 | SwiftSwift |
许可证 | MIT |
发布日期最新版本发布日期 | 2016年10月 |
SPM支持 SPM | ✗ |
由 kaizeiyimi 维护。
TextKit 功能强大但复杂。它为文本添加了附件,以便与文本一起绘制图像。但是,所有内容都是绘制,没有任何视图可以与文本一起布局。
XLYTextKitExtension 为 TextKit 添加了布局文本和视图的能力。
它使用 NSTextAttachment
来实现这样的功能。视图或文本可以嵌入到一个附件中,作为一个 glyph
。背景 和 前景 的 glyphs 也有机会绘制您的自定义内容,只需将一个 XLYPainter
添加到 AttributedText
中即可。
提供了许多辅助绘制函数,如果您需要,可以编写自己的函数。
这是创建附件或添加属性的熟悉方式。 XLYTextAttachment
是 NSTextAttachment
的一个子类。
狗正在蹲下又站起来。看演示了解效果。这里只是一个静态图像。文本可编辑。
let gifAttachment = XLYTextAttachment { () -> UIView in
let animatedImageView = UIImageView()
animatedImageView.backgroundColor = .purpleColor()
animatedImageView.animationImages = images
animatedImageView.animationDuration = 0.6
animatedImageView.startAnimating()
return animatedImageView
}
// can adjust origin as you wish, just same as normal attachment config
gifAttachment.bounds = CGRectMake(0, 0, 50, 50)
let text = NSAttributedString(attachment: gifAttachment)
let painterAttachment = XLYTextAttachment { (context: CGContext, rect: CGRect) in
// you can draw whatever you want
UIColor.redColor().setFill()
CGContextFillRect(context, rect)
}
let text = NSAttributedString(attachment: gifAttachment)
XLYTextAttachment
仍然可以使用作为 NSTextAttachment
。它不会改变任何事情。// just create as if it is NSTextAttachment
let imageAttachment = XLYTextAttachment()
imageAttachment.image = UIImage(named: "dog0")
let text = NSAttributedString(attachment: gifAttachment)
let combined1Attachment = XLYTextAttachment(string: "[email protected]",
lineFragmentPadding: 10,
insets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10),
baselineMode: .LineUsedRectBottom(diff: 0))
let text = NSAttributedString(attachment: combined1Attachment)
有一个枚举 'XLYPainter.PainterType' 包含 Background
和 Foreground
。
// fillLineUsedRect is a helper method, it returns a function handling how to draw.
let backgroundPainter = XLYPainter(type: .Background, handler: fillLineUsedRect(UIColor.purpleColor(), cornerFactor: 0.5))
// another helper method. draws the glyph outline.
let outlinePainter = XLYPainter(type: .Foreground, handler: strokeOutline(UIColor.redColor(), lineDashLengths:[2, 2]))
// create attributes as you always do. key canbe any string.
let attributes = [ "your.painter.key.background": backgroundPainter,
"another.painter.outlinePainter": outlinePainter]
text.addAttributes(atrributes, range: NSMakeRange(0, storage.length))
相当复杂。您仍然需要编写很多代码,但我的目标是向 TextKit 添加一些功能,而不是简化它。
您可以通过在 UITextView
上调用扩展方法 setUseXLYLayoutManager()
来在 UITextView
上使用 XLYTextKitExtension
。或者您也可以编写自己的视图并在 drawRect(_:)
中绘制gly。请参见演示示例。