Implement highlighting

This commit is contained in:
Indragie Karunaratne
2015-04-28 16:13:51 -06:00
parent 54a8af816e
commit 59ac7b2793
2 changed files with 40 additions and 2 deletions

View File

@@ -9,17 +9,37 @@
import UIKit
public class RegularExpressionTextStorage: NSTextStorage {
private struct Expression {
let regex: NSRegularExpression
let attributes: [String: AnyObject]
}
private let backingStore: NSMutableAttributedString
private var expressions = [Expression]()
private var defaultAttributes: [String: AnyObject] = [
NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
] {
didSet {
highlightRange(NSRange(location: 0, length: (backingStore.string as NSString).length))
}
}
// MARK: API
public func addRegularExpression(expression: NSRegularExpression, withAttributes attributes: [String: AnyObject]) {
expressions.append(Expression(regex: expression, attributes: attributes))
edited(.EditedAttributes, range: NSRange(location: 0, length: backingStore.length), changeInLength: 0)
}
// MARK: Initialization
public override init() {
backingStore = NSMutableAttributedString()
backingStore = NSMutableAttributedString(string: "", attributes: defaultAttributes)
super.init()
}
required public init(coder aDecoder: NSCoder) {
backingStore = NSMutableAttributedString()
backingStore = NSMutableAttributedString(string: "", attributes: defaultAttributes)
super.init(coder: aDecoder)
}
@@ -42,4 +62,21 @@ public class RegularExpressionTextStorage: NSTextStorage {
backingStore.setAttributes(attrs, range: range)
edited(.EditedAttributes, range: range, changeInLength: 0)
}
public override func processEditing() {
let lineRange = (backingStore.string as NSString).lineRangeForRange(editedRange)
highlightRange(lineRange)
super.processEditing()
}
private func highlightRange(range: NSRange) {
setAttributes(defaultAttributes, range: range)
backingStore.beginEditing()
for expression in expressions {
expression.regex.enumerateMatchesInString(backingStore.string, options: nil, range: range) { (result, _, _) in
self.addAttributes(expression.attributes, range: result.range)
}
}
backingStore.endEditing()
}
}

View File

@@ -16,6 +16,7 @@ class ViewController: UIViewController {
let layoutManager = NSLayoutManager()
layoutManager.addTextContainer(textContainer)
let textStorage = RegularExpressionTextStorage()
textStorage.addRegularExpression(NSRegularExpression(pattern: "\\*\\*[\\w\\d]+\\*\\*", options: nil, error: nil)!, withAttributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(17)])
textStorage.addLayoutManager(layoutManager)
let textView = UITextView(frame: CGRectZero, textContainer: textContainer)