blob: d27a472e14cc97ac104f666ce6115e152bcba02a (
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
|
//
// NSAttributedString+Markdown.swift
// MullvadVPN
//
// Created by pronebird on 19/11/2021.
// Copyright © 2021 Mullvad VPN AB. All rights reserved.
//
import UIKit
extension NSAttributedString {
convenience init(
markdownString: String,
font: UIFont,
applyEffect: ((String) -> [NSAttributedString.Key: Any])? = nil
) {
let attributedString = NSMutableAttributedString()
let components = markdownString.components(separatedBy: "**")
let fontDescriptor = font.fontDescriptor.withSymbolicTraits(.traitBold) ?? font
.fontDescriptor
let boldFont = UIFont(descriptor: fontDescriptor, size: font.pointSize)
for (index, string) in components.enumerated() {
var attributes = [NSAttributedString.Key: Any]()
if index % 2 == 0 {
attributes[.font] = font
} else {
attributes[.font] = boldFont
attributes.merge(applyEffect?(string) ?? [:], uniquingKeysWith: { $1 })
}
attributedString.append(NSAttributedString(string: string, attributes: attributes))
}
self.init(attributedString: attributedString)
}
}
|