我正在尝试通过测试项目更好地理解Markdown支持。我使用MardownTextView
项目作为指南 - 在https://github.com/indragiek/MarkdownTextView找到。
我已将MarkdownKit
框架添加到我的测试项目中。
我的textViewExample
项目与MarkdownTextView
项目之间的区别在于我在故事板中添加了UITextView
,而MarkdownTextView
以编程方式添加了它。
以下是MarkdownTextView
项目如何使用框架添加UITextView
和降价支持。
import UIKit
import MarkdownTextView
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let attributes = MarkdownAttributes()
let textStorage = MarkdownTextStorage(attributes: attributes)
do {
textStorage.addHighlighter(try LinkHighlighter())
} catch let error {
fatalError("Error initializing LinkHighlighter: \(error)")
}
textStorage.addHighlighter(MarkdownStrikethroughHighlighter())
textStorage.addHighlighter(MarkdownSuperscriptHighlighter())
if let codeBlockAttributes = attributes.codeBlockAttributes {
textStorage.addHighlighter(MarkdownFencedCodeHighlighter(attributes: codeBlockAttributes))
}
let textView = MarkdownTextView(frame: CGRectZero, textStorage: textStorage)
textView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(textView)
let views = ["textView": textView]
var constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[textView]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[textView]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
NSLayoutConstraint.activateConstraints(constraints)
}
}
测试项目
我已将UITextView
添加到故事板中的视图控制器和约束中。所以我尝试通过以下方式添加支持;
import UIKit
import MarkdownKit
@IBOutlet weak var textView: MarkdownTextView!
var textStorage: MarkdownTextStorage?
class TextViewController: UIViewController, UITextViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let attributes = MarkdownAttributes()
let textStorage = MarkdownTextStorage(attributes: attributes)
do {
textStorage.addHighlighter(try LinkHighlighter())
} catch let error {
fatalError("Error initializing LinkHighlighter: \(error)")
}
textStorage.addHighlighter(MarkdownStrikethroughHighlighter())
textStorage.addHighlighter(MarkdownSuperscriptHighlighter())
if let codeBlockAttributes = attributes.codeBlockAttributes {
textStorage.addHighlighter(MarkdownFencedCodeHighlighter(attributes: codeBlockAttributes))
}
//Error - Apply textStorage to textview that has already been created
textView.textStorage = textStorage
}
}
然而我收到了错误
无法分配属性:' textStorage'是一个只获得属性
如何在示例项目已经完成的情况下使用框架在项目中添加textView
的markdown支持,而无需以编程方式添加UITextView
?
答案 0 :(得分:1)
使用textView' layoutManager
处理其TextStorage
:
if let lm = self.textView.layoutManager{
lm.replaceTextStorage(textStorage)
}
您可以在Apple的NSLayoutManager
class