summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/NSAttributedString+Markdown.swift
blob: af13fb5b95b608770d14ea1413f39a18a7c7db9b (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
//
//  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) {
        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
            }

            attributedString.append(NSAttributedString(string: string, attributes: attributes))
        }

        self.init(attributedString: attributedString)
    }
}