blob: fd9ebc5e7efcc476d0f34954fee9ca84de2f53ad (
plain)
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
|
//
// NSAttributedString+Markdown.swift
// MullvadVPN
//
// Created by pronebird on 19/11/2021.
// Copyright © 2025 Mullvad VPN AB. All rights reserved.
//
import UIKit
extension NSAttributedString {
enum MarkdownElement {
case bold
}
convenience init(
markdownString: String,
options: MarkdownStylingOptions,
applyEffect: ((MarkdownElement, String) -> [NSAttributedString.Key: Any])? = nil
) {
let attributedString = NSMutableAttributedString()
let components = markdownString.components(separatedBy: "**")
for (stringIndex, string) in components.enumerated() {
var attributes: [NSAttributedString.Key: Any] = [:]
if stringIndex % 2 == 0 {
attributes[.font] = options.font
} else {
attributes[.font] = options.font.withWeight(.bold)
attributes.merge(applyEffect?(.bold, string) ?? [:], uniquingKeysWith: { $1 })
}
attributedString.append(NSAttributedString(string: string, attributes: attributes))
}
attributedString.addAttribute(
.paragraphStyle,
value: options.paragraphStyle,
range: NSRange(location: 0, length: attributedString.length)
)
self.init(attributedString: attributedString)
}
}
extension NSMutableAttributedString {
func apply(paragraphStyle: NSParagraphStyle) {
let attributeRange = NSRange(location: 0, length: length)
addAttribute(.paragraphStyle, value: paragraphStyle, range: attributeRange)
}
}
|