-
Notifications
You must be signed in to change notification settings - Fork 290
/
Copy pathSPTextView.swift
95 lines (78 loc) · 2.7 KB
/
SPTextView.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
//
// SPTextView.swift
// Simplenote
//
// Created by Charlie Scheer on 12/19/24.
// Copyright © 2024 Automattic. All rights reserved.
//
extension SPTextView {
@objc
func setupTextContainer(with textStorage: SPInteractiveTextStorage) -> NSTextContainer {
let container = NSTextContainer(size: .zero)
container.widthTracksTextView = true
container.heightTracksTextView = true
if #available(iOS 16.0, *) {
let textLayoutManager = NSTextLayoutManager()
let contentStorage = NSTextContentStorage()
contentStorage.delegate = self
contentStorage.addTextLayoutManager(textLayoutManager)
textLayoutManager.textContainer = container
} else {
let layoutManager = NSLayoutManager()
layoutManager.addTextContainer(container)
textStorage.addLayoutManager(layoutManager)
}
return container
}
}
// MARK: NSTextContentStorageDelegate
//
extension SPTextView: NSTextContentStorageDelegate {
public func textContentStorage(_ textContentStorage: NSTextContentStorage, textParagraphWith range: NSRange) -> NSTextParagraph? {
guard let originalText = textContentStorage.textStorage?.attributedSubstring(from: range) as? NSMutableAttributedString else {
return nil
}
let style = textInRangeIsHeader(range) ? headlineStyle : defaultStyle
originalText.addAttributes(style, range: originalText.fullRange)
return NSTextParagraph(attributedString: originalText)
}
func textInRangeIsHeader(_ range: NSRange) -> Bool {
range.location == .zero
}
// MARK: Styles
//
var headlineFont: UIFont {
UIFont.preferredFont(for: .title1, weight: .bold)
}
var defaultFont: UIFont {
UIFont.preferredFont(forTextStyle: .body)
}
var defaultTextColor: UIColor {
UIColor.simplenoteNoteHeadlineColor
}
var lineSpacing: CGFloat {
defaultFont.lineHeight * Metrics.lineSpacingMultipler
}
var defaultStyle: [NSAttributedString.Key: Any] {
[
.font: defaultFont,
.foregroundColor: defaultTextColor,
.paragraphStyle: NSMutableParagraphStyle(lineSpacing: lineSpacing)
]
}
var headlineStyle: [NSAttributedString.Key: Any] {
[
.font: headlineFont,
.foregroundColor: defaultTextColor,
]
}
}
// MARK: - Metrics
//
private enum Metrics {
static let lineSpacingMultiplerPad: CGFloat = 0.40
static let lineSpacingMultiplerPhone: CGFloat = 0.20
static var lineSpacingMultipler: CGFloat {
UIDevice.isPad ? lineSpacingMultiplerPad : lineSpacingMultiplerPhone
}
}