-
Notifications
You must be signed in to change notification settings - Fork 686
/
ActiveLabel.swift
350 lines (290 loc) · 11.5 KB
/
ActiveLabel.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
//
// ActiveLabel.swift
// ActiveLabel
//
// Created by Johannes Schickling on 9/4/15.
// Copyright © 2015 Optonaut. All rights reserved.
//
import Foundation
import UIKit
public class ActiveLabel: UILabel {
// MARK: - public properties
public var mentionEnabled: Bool = true {
didSet {
updateTextStorage()
}
}
public var hashtagEnabled: Bool = true {
didSet {
updateTextStorage()
}
}
public var URLEnabled: Bool = true {
didSet {
updateTextStorage()
}
}
public var mentionColor: UIColor = .blueColor() {
didSet {
updateTextStorage()
}
}
public var mentionSelectedColor: UIColor? {
didSet {
updateTextStorage()
}
}
public var hashtagColor: UIColor = .blueColor() {
didSet {
updateTextStorage()
}
}
public var hashtagSelectedColor: UIColor? {
didSet {
updateTextStorage()
}
}
public var URLColor: UIColor = .blueColor() {
didSet {
updateTextStorage()
}
}
public var URLSelectedColor: UIColor? {
didSet {
updateTextStorage()
}
}
public var lineSpacing: Float? {
didSet {
updateTextStorage()
}
}
// MARK: - public methods
public func handleMentionTap(handler: (String) -> ()) {
mentionTapHandler = handler
}
public func handleHashtagTap(handler: (String) -> ()) {
hashtagTapHandler = handler
}
public func handleURLTap(handler: (NSURL) -> ()) {
urlTapHandler = handler
}
// MARK: - override UILabel properties
override public var text: String? {
didSet {
updateTextStorage()
}
}
override public var attributedText: NSAttributedString? {
didSet {
updateTextStorage()
}
}
override public var font: UIFont! {
didSet {
updateTextStorage()
}
}
override public var textColor: UIColor! {
didSet {
updateTextStorage()
}
}
// MARK: - init functions
override public init(frame: CGRect) {
super.init(frame: frame)
setupLabel()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLabel()
}
public override func drawTextInRect(rect: CGRect) {
let range = NSRange(location: 0, length: textStorage.length)
textContainer.size = rect.size
layoutManager.drawBackgroundForGlyphRange(range, atPoint: rect.origin)
layoutManager.drawGlyphsForGlyphRange(range, atPoint: rect.origin)
}
public override func sizeThatFits(size: CGSize) -> CGSize {
let currentSize = textContainer.size
defer {
textContainer.size = currentSize
}
textContainer.size = size
return layoutManager.usedRectForTextContainer(textContainer).size
}
// MARK: - touch events
func onTouch(gesture: UILongPressGestureRecognizer) {
let location = gesture.locationInView(self)
switch gesture.state {
case .Began, .Changed:
if let element = elementAtLocation(location) {
if element.range.location != selectedElement?.range.location || element.range.length != selectedElement?.range.length {
updateAttributesWhenSelected(false)
selectedElement = element
updateAttributesWhenSelected(true)
}
} else {
updateAttributesWhenSelected(false)
selectedElement = nil
}
case .Cancelled, .Ended:
guard let selectedElement = selectedElement else {
return
}
switch selectedElement.element {
case .Mention(let userHandle): mentionTapHandler?(userHandle)
case .Hashtag(let hashtag): hashtagTapHandler?(hashtag)
case .URL(let url): urlTapHandler?(url)
case .None: ()
}
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC)))
dispatch_after(when, dispatch_get_main_queue()) {
self.updateAttributesWhenSelected(false)
self.selectedElement = nil
}
default: ()
}
}
// MARK: - private properties
private var mentionTapHandler: ((String) -> ())?
private var hashtagTapHandler: ((String) -> ())?
private var urlTapHandler: ((NSURL) -> ())?
private var selectedElement: (range: NSRange, element: ActiveElement)?
private lazy var textStorage = NSTextStorage()
private lazy var layoutManager = NSLayoutManager()
private lazy var textContainer = NSTextContainer()
private lazy var activeElements: [ActiveType: [(range: NSRange, element: ActiveElement)]] = [
.Mention: [],
.Hashtag: [],
.URL: [],
]
// MARK: - helper functions
private func setupLabel() {
textStorage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(textContainer)
textContainer.lineFragmentPadding = 0
let touchRecognizer = UILongPressGestureRecognizer(target: self, action: "onTouch:")
touchRecognizer.minimumPressDuration = 0.00001
touchRecognizer.delegate = self
addGestureRecognizer(touchRecognizer)
userInteractionEnabled = true
}
private func updateTextStorage() {
guard let attributedText = attributedText else {
return
}
// clean up previous active elements
for (type, _) in activeElements {
activeElements[type]?.removeAll()
}
guard attributedText.length > 0 else {
return
}
let mutAttrString = addLineBreak(attributedText)
parseTextAndExtractActiveElements(mutAttrString)
addLinkAttribute(mutAttrString)
textStorage.setAttributedString(mutAttrString)
setNeedsDisplay()
}
/// add link attribute
private func addLinkAttribute(mutAttrString: NSMutableAttributedString) {
var range = NSRange(location: 0, length: 0)
var attributes = mutAttrString.attributesAtIndex(0, effectiveRange: &range)
attributes[NSFontAttributeName] = font!
attributes[NSForegroundColorAttributeName] = textColor
mutAttrString.addAttributes(attributes, range: range)
attributes[NSForegroundColorAttributeName] = mentionColor
for (type, elements) in activeElements {
switch type {
case .Mention: attributes[NSForegroundColorAttributeName] = mentionColor
case .Hashtag: attributes[NSForegroundColorAttributeName] = hashtagColor
case .URL: attributes[NSForegroundColorAttributeName] = URLColor
case .None: ()
}
for element in elements {
mutAttrString.setAttributes(attributes, range: element.range)
}
}
}
/// use regex check all link ranges
private func parseTextAndExtractActiveElements(attrString: NSAttributedString) {
let textString = attrString.string as NSString
for word in textString.componentsSeparatedByString(" ") {
let element = activeElement(word)
switch element {
case .Mention(let userHandle) where mentionEnabled:
activeElements[.Mention]?.append((textString.rangeOfString("@\(userHandle)"), element))
case .Hashtag(let hashtag) where hashtagEnabled:
activeElements[.Hashtag]?.append((textString.rangeOfString("#\(hashtag)"), element))
case .URL(let url) where URLEnabled:
activeElements[.URL]?.append((textString.rangeOfString(url.absoluteString), element))
default: ()
}
}
}
/// add line break mode
private func addLineBreak(attrString: NSAttributedString) -> NSMutableAttributedString {
let mutAttrString = NSMutableAttributedString(attributedString: attrString)
var range = NSRange(location: 0, length: 0)
var attributes = mutAttrString.attributesAtIndex(0, effectiveRange: &range)
let paragraphStyle = attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping
if let lineSpacing = lineSpacing {
paragraphStyle.lineSpacing = CGFloat(lineSpacing)
}
attributes[NSParagraphStyleAttributeName] = paragraphStyle
mutAttrString.setAttributes(attributes, range: range)
return mutAttrString
}
private func updateAttributesWhenSelected(isSelected: Bool) {
guard let selectedElement = selectedElement else {
return
}
var attributes = textStorage.attributesAtIndex(0, effectiveRange: nil)
if isSelected {
switch selectedElement.element {
case .Mention(_): attributes[NSForegroundColorAttributeName] = mentionColor
case .Hashtag(_): attributes[NSForegroundColorAttributeName] = hashtagColor
case .URL(_): attributes[NSForegroundColorAttributeName] = URLColor
case .None: ()
}
} else {
switch selectedElement.element {
case .Mention(_): attributes[NSForegroundColorAttributeName] = mentionSelectedColor ?? mentionColor
case .Hashtag(_): attributes[NSForegroundColorAttributeName] = hashtagSelectedColor ?? hashtagColor
case .URL(_): attributes[NSForegroundColorAttributeName] = URLSelectedColor ?? URLColor
case .None: ()
}
}
textStorage.addAttributes(attributes, range: selectedElement.range)
setNeedsDisplay()
}
private func elementAtLocation(location: CGPoint) -> (range: NSRange, element: ActiveElement)? {
guard textStorage.length > 0 else {
return nil
}
let boundingRect = layoutManager.boundingRectForGlyphRange(NSRange(location: 0, length: textStorage.length), inTextContainer: textContainer)
guard boundingRect.contains(location) else {
return nil
}
let index = layoutManager.glyphIndexForPoint(location, inTextContainer: textContainer)
for element in activeElements.map({ $0.1 }).flatten() {
if index >= element.range.location && index <= element.range.location + element.range.length {
return element
}
}
return nil
}
}
extension ActiveLabel: UIGestureRecognizerDelegate {
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOfGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}