-
Notifications
You must be signed in to change notification settings - Fork 0
/
Styler.swift
557 lines (418 loc) · 18.2 KB
/
Styler.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//
// Styler.swift
// Styler
//
// Created by Anton on 24/07/2017.
// Copyright © 2017 Anton Lovchikov. All rights reserved.
//
import Foundation
import UIKit
/// The class allows to set and update styled text of UILabels by using easy API:
///
/// - `var styledText: NSAttributedString?`
/// - `func updateStyledText(_ newText: String)`
class StyledLabel : UILabel {
/// Sets prepared styled text.
///
/// You can compose `NSAttributedString` by yourself
/// or you can use plain `String` and attach a `TextStyle` to it.
///
/// "Hello world".with(mainTextStyle)
var styledText : NSAttributedString? {
didSet {
self.attributedText = styledText
}
}
/// Updates text using current `TextStyle`.
/// - parameters:
/// - newText: Plain `String` to be set as text.
/// Current label `textStyle` will be applied automatically.
///
/// Use this method if you need to update the text in the run time, but you don't want to deal with `textStyle` again.
func updateStyledText(_ newText: String) {
let attributedString = NSMutableAttributedString(string:newText)
// Get current attributes
let attributes = attributedText?.attributes(at:0, longestEffectiveRange:nil, in:attributedString.range)
// Apply current attributes to the new string
if let attributes = attributes {
attributedString.addAttributes(attributes, range:NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
} else {
self.text = newText
}
}
}
/// The class allows to set and update styled text of UITextView by using easy API:
///
/// - `var styledText: NSAttributedString?`
/// - `func updateStyledText(_ newText: String)`
class StyledTextView: UITextView {
/// Sets prepared styled text.
///
/// You can compose `NSAttributedString` by yourself
/// or you can use plain `String` and attach a `TextStyle` to it.
///
/// "Hello world".with(mainTextStyle)
var styledText : NSAttributedString? {
didSet {
self.attributedText = styledText
}
}
/// Updates text using current `TextStyle`.
/// - parameters:
/// - newText: Plain `String` to be set as text.
/// Current text view `textStyle` will be applied automatically.
///
/// Use this method if you need to update the text in the run time, but you don't want to deal with `textStyle` again.
func updateStyledText(_ newText: String) {
let attributedString = NSMutableAttributedString(string:newText)
// Get current attributes
let attributes = attributedText?.attributes(at:0, longestEffectiveRange:nil, in:attributedString.range)
// Apply current attributes to the new string
if let attributes = attributes {
attributedString.addAttributes(attributes, range:NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
} else {
self.text = newText
}
}
}
/// The class allows to set and update styled text of UITextField by using easy API:
///
/// - `var styledText: NSAttributedString?`
/// - `func updateStyledText(_ newText: String)`
/// - `var styledPlaceholder: NSAttributedString?`
/// - `func updateStyledPlaceholder(_ newText: String)`
class StyledTextField: UITextField {
/// Sets prepared style.
///
/// Call it if you need to prepare the textField without setting initial text to it
var style: TextStyle? {
didSet {
if let styleSecured = style {
self.defaultTextAttributes = styleSecured.attributes()
}
}
}
/// Sets prepared styled text.
///
/// You can compose `NSAttributedString` by yourself
/// or you can use plain `String` and attach a `TextStyle` to it.
///
/// "Hello world".with(mainTextStyle)
var styledText : NSAttributedString? {
didSet {
if let attrTextSecured = styledText {
self.attributedText = attrTextSecured
if attrTextSecured.string.count > 0 {
let attributes = attrTextSecured.attributes(at:0, longestEffectiveRange:nil, in:attrTextSecured.range)
var stringAttributes : [String : Any] = [:]
for attr in attributes {
stringAttributes[attr.key.rawValue] = attr.value
}
self.defaultTextAttributes = stringAttributes
} else {
NSLog("To set a style without setting initial text, use UITextField.style attribute")
}
}
}
}
/// Updates text using current `TextStyle`.
/// - parameters:
/// - newText: Plain `String` to be set as text.
/// Current text field text `textStyle` will be applied automatically.
///
/// Use this method if you need to update the text in the run time, but you don't want to deal with `textStyle` again.
func updateStyledText(_ newText: String) {
let attributedString = NSMutableAttributedString(string:newText)
// Get current attributes
let attributes = self.attributedText?.attributes(at:0, longestEffectiveRange:nil, in:attributedString.range)
if let attributes = attributes {
attributedString.addAttributes(attributes, range:NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
} else {
self.text = newText
}
}
/// Sets prepared styled placeholder.
///
/// You can compose `NSAttributedString` by yourself
/// or you can use plain `String` and attach a `TextStyle` to it.
///
/// "Hello world".with(mainTextStyle)
var styledPlaceholder : NSAttributedString? {
didSet {
if let attrTextSecured = styledPlaceholder {
self.attributedPlaceholder = attrTextSecured
}
}
}
/// Updates placeholder using current `TextStyle`.
/// - parameters:
/// - newText: Plain `String` to be set as placeholder.
/// Current text field placeholder `textStyle` will be applied automatically.
///
/// Use this method if you need to update the placeholder in the run time, but you don't want to deal with `textStyle` again.
func updateStyledPlaceholder(_ newPlaceholder: String) {
let attributedString = NSMutableAttributedString(string:newPlaceholder)
// Get current attributes
let attributes = attributedText?.attributes(at:0, longestEffectiveRange:nil, in:NSRange(location: 0, length: attributedString.length))
if let attributes = attributes {
attributedString.addAttributes(attributes, range:NSMakeRange(0, attributedString.length))
self.attributedPlaceholder = attributedString
} else {
self.placeholder = newPlaceholder
}
}
}
/// The class allows to set and update styled title of UIButton by using easy API:
///
/// - `func setStyledTitle(_ title: NSAttributedString, for state: UIControlState)`
/// - `func updateStyledTitle(_ newTitle: String, for state: UIControlState)`
class StyledButton : UIButton {
/// Sets prepared styled title for state.
///
/// - parameters:
/// - title: `NSAttributedString` with desired style applied
/// - state: `UIControlState`for which the title should be set
///
/// You can compose `NSAttributedString` by yourself
/// or you can use plain `String` and attach a `TextStyle` to it.
///
/// "Hello world".with(mainTextStyle)
func setStyledTitle(_ title: NSAttributedString, for state: UIControlState) {
self.setAttributedTitle(title, for:state)
}
/// Updates title using current `TextStyle`.
/// - parameters:
/// - newTitle: Plain `String` to be set as title.
/// Current button title `textStyle` for given `state` will be applied automatically.
/// - state: `UIControlState`for which the title should be updated
///
/// Use this method if you need to update the placeholder in the run time, but you don't want to deal with `textStyle` again.
func updateStyledTitle(_ newTitle: String, for state: UIControlState) {
let attributedString = NSMutableAttributedString(string:newTitle)
// Get current attributes
let attributes = self.attributedTitle(for:state)?.attributes(at:0, longestEffectiveRange:nil, in:NSRange(location: 0, length: attributedString.length))
if let attributes = attributes {
attributedString.addAttributes(attributes, range:NSMakeRange(0, attributedString.length))
self.setAttributedTitle(attributedString, for:state)
} else {
self.setTitle(newTitle, for:state)
}
}
}
/// The extension allows to attach a `TextStyle` by using:
///
/// - `func with(_ style:TextStyle) -> NSAttributedString`
extension String {
/// Attaches a `TextStyle` and composes an NSAttributedString.
/// - parameters:
/// - style: A prepared `TextStyle`
///
/// - returns:
/// An NSAttributedString ready to be set as `attributedText`
///
/// Use this method if you need to update the placeholder in the run time, but you don't want to deal with `textStyle` again.
func with(_ style:TextStyle) -> NSAttributedString {
return style.composeAttributedString(with:self)
}
}
/// The struct storing styles you composed.
struct TextStyle : Hashable {
var fontName : String
// PostScript name. System font name by default
var fontSize : CGFloat
// In points. System size (17 points) by default
fileprivate var font : UIFont
// Composed font
var lineSpacing : CGFloat
// Absolute value in points (pick it right from a Sketch file).
// Standard font line-height by default
fileprivate var relativeLineSpacing : CGFloat
// Relative value representing additional spacing value
var characterSpacing : CGFloat
// In points. 0 by default
var textColor : UIColor
// Black by default
var backgroundColor : UIColor
// Clear by default
var underlineStyle : NSUnderlineStyle
// None by default
var strickingStyle : NSUnderlineStyle
// None by default
var alignment : NSTextAlignment
// Natural by default
/// Creates a `TextView` struct.
/// - parameters:
/// - fontName: **PostScript** name. System font name by default
/// - fontSize: In points. System size (17 points) by default
/// - lineSpacing: **Absolute value** in points (pick it right from a Sketch file). Standard font line-height by default
/// - characterSpacing: Aka Kerning. 0 by default
/// - color: A prepared UIColor. Black by default
/// - alignment: An NSTextAlignment. Natural by default
///
/// You can set only parameters you care about. Parameters you haven't provided will be set to the default values.
init(fontName: String = UIFont.systemFont(ofSize:1).fontName,
fontSize: CGFloat = UIFont.systemFontSize,
lineSpacing: CGFloat? = nil,
characterSpacing: CGFloat = 0,
textColor: UIColor = UIColor.black,
backgroundColor: UIColor = UIColor.clear,
underlineStyle: NSUnderlineStyle = .styleNone,
strickingStyle: NSUnderlineStyle = .styleNone,
alignment : NSTextAlignment = .natural){
self.fontName = fontName
self.fontSize = fontSize
let composedFont = UIFont(name:fontName, size:fontSize)
self.font = (composedFont != nil) ? composedFont! : UIFont.systemFont(ofSize:UIFont.systemFontSize)
// Prepare relative line spacing
if let lineSpacing = lineSpacing {
self.lineSpacing = lineSpacing
if let lineHeight = UIFont(name:fontName, size:fontSize)?.lineHeight {
self.relativeLineSpacing = lineSpacing - lineHeight
} else {
self.relativeLineSpacing = lineSpacing - 20 // Default value
}
} else {
self.relativeLineSpacing = 0
if let lineHeight = UIFont(name:fontName, size:fontSize)?.lineHeight {
self.lineSpacing = lineHeight
} else {
self.lineSpacing = 20
}
}
self.characterSpacing = characterSpacing
self.textColor = textColor
self.backgroundColor = backgroundColor
self.underlineStyle = underlineStyle
self.strickingStyle = strickingStyle
self.alignment = alignment
}
/// Changes fontSize property of the basic style
mutating func fontName(_ fontName: String) -> TextStyle {
self.fontName = fontName
if let font = UIFont(name:fontName, size:fontSize) {
self.font = font
}
return self
}
/// Changes fontSize property of the basic style
mutating func fontSize(_ fontSize: CGFloat) -> TextStyle {
self.fontSize = fontSize
if let font = UIFont(name:self.font.fontName, size:fontSize) {
self.font = font
}
return self
}
/// Changes lineSpacing property of the basic style
mutating func lineSpacing(_ lineSpacing: CGFloat) -> TextStyle {
self.lineSpacing = lineSpacing
return self
}
/// Changes characterSpacing property of the basic style
mutating func characterSpacing(_ spacing: CGFloat) -> TextStyle {
self.characterSpacing = spacing
return self
}
/// Changes textColor property of the basic style
mutating func textColor(_ color: UIColor) -> TextStyle {
self.textColor = color
return self
}
/// Changes backgroundColor property of the basic style
mutating func backgroundColor(_ backgroundColor: UIColor) -> TextStyle {
self.backgroundColor = backgroundColor
return self
}
/// Changes underlineStyle property of the basic style
mutating func underlineStyle(_ underlineStyle: NSUnderlineStyle) -> TextStyle {
self.underlineStyle = underlineStyle
return self
}
/// Changes strickingStyle property of the basic style
mutating func strickingStyle(_ strickingStyle: NSUnderlineStyle) -> TextStyle {
self.strickingStyle = strickingStyle
return self
}
/// Changes alignment property of the basic style
mutating func alignment(_ alignment: NSTextAlignment) -> TextStyle {
self.alignment = alignment
return self
}
}
// Technical stuff
extension String {
fileprivate var range : NSRange {
get {
return NSRange(location: 0, length: self.count)
}
}
}
extension NSAttributedString {
fileprivate var range : NSRange {
get {
return NSRange(location: 0, length: self.length)
}
}
}
extension TextStyle {
fileprivate func composeAttributedString(with text:String) -> NSAttributedString {
// Text preparation
let attributedString = NSMutableAttributedString(string:text)
// Compose text attributes
let attributes = self.сomposeAttributes()
// Apply attributes
attributedString.addAttributes(attributes, range:NSMakeRange(0, attributedString.length))
return attributedString
}
private func сomposeAttributes() -> [NSAttributedStringKey : Any] {
var attributes : [NSAttributedStringKey : Any] = [:]
// Apply font parameter
attributes[NSAttributedStringKey.font] = self.font
// Apply text color parameter
attributes[NSAttributedStringKey.foregroundColor] = self.textColor
// Apply background color parameter
attributes[NSAttributedStringKey.backgroundColor] = self.backgroundColor
// Apply undercrossing
attributes[NSAttributedStringKey.underlineStyle] = self.underlineStyle.rawValue
// Apply stricking
attributes[NSAttributedStringKey.strikethroughStyle] = NSNumber(value: self.strickingStyle.rawValue)
// Apply line spacing
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = self.relativeLineSpacing
// Apply alignment
paragraphStyle.alignment = self.alignment
attributes[NSAttributedStringKey.paragraphStyle] = paragraphStyle
// Apply character spacing
attributes[NSAttributedStringKey.kern] = self.characterSpacing
return attributes
}
func attributes() -> [String : Any] {
let attributes = self.сomposeAttributes()
var translatedAttrs: [String : Any] = [:]
for (key, value) in attributes {
translatedAttrs[key.rawValue] = value
}
return translatedAttrs
}
var hashValue: Int {
get {
let fontNameHash = fontName.hashValue
let fontSizeHash = fontSize.hashValue
let lineSpacingHash = lineSpacing.hashValue
let relativeLineSpacingHash = relativeLineSpacing.hashValue
let characterSpacingHash = characterSpacing.hashValue
let textColorHash = textColor.hashValue
let backgroundColorHash = backgroundColor.hashValue
let underlineStyleHash = underlineStyle.hashValue
let strickingStyleHash = strickingStyle.hashValue
let alignmentHash = alignment.hashValue
return fontNameHash + fontSizeHash + lineSpacingHash + relativeLineSpacingHash + characterSpacingHash + textColorHash + backgroundColorHash + underlineStyleHash + strickingStyleHash + alignmentHash
}
}
static func == (lhs: TextStyle, rhs: TextStyle) -> Bool {
return
lhs.hashValue == rhs.hashValue
}
}