gonzalezreal / swift-markdown-ui

Display and customize Markdown text in SwiftUI
MIT License
2.26k stars 267 forks source link

Accessibility - Font Size dynamically change #41

Closed heltena closed 3 years ago

heltena commented 3 years ago

Hello!

I'm working with this package (thanks! it is great!) and I'm having troubles on debugging the Accessibility font size. Also, it is an issue that could be problematic in production.

I open the "Accessibility Inspector" and the Markdown view looks great if the font size is set to big (50 pt, I guess). The problem is the current view is not observing the UIContentSizeCategory.didChangeNotification notification and I cannot debug properly the view, changing the font size while running.

I'm doing this right now:

import SwiftUI
import MarkdownUI

private struct InvalidateMarkdown: View {
    var document: Document
    var styleGenerator: () -> MarkdownStyle
    @State var style: MarkdownStyle

    init(document: Document, style styleGenerator: (() -> MarkdownStyle)? = nil) {
        self.document = document
        self.styleGenerator =  {
            if let styleGenerator = styleGenerator {
                return styleGenerator()
            } else {
                return DefaultMarkdownStyle(font: .system(.body))
            }
        }
        self._style = State(initialValue: self.styleGenerator())
    }

    init(_ content: String, style: (() -> MarkdownStyle)? = nil) {
        let document = Document(content)
        self.init(document: document, style: style)
    }

    var body: some View {
        Markdown(document)
            .markdownStyle(style)
            .onReceive(NotificationCenter.default.publisher(for: UIContentSizeCategory.didChangeNotification)) { _ in
                self.style = styleGenerator()
            }
    }
}

struct ContentView: View {
    var body: some View {
        VStack {
            InvalidateMarkdown(
                """
                # Header
                * test

                Just a text example **bold**, *italic* `code`
                """)
            {
                DefaultMarkdownStyle(font: .system(.body))
            }
            Spacer()
        }
    }
}

Where, basically, I'm changing the style everytime the "didChangeNotification" arrives. It is not great, and I'm not proud of it. I keep looking your code, but it will be great if you could have a look.

Thanks!!!!!

heltena commented 3 years ago

Sorry, I solved creating a new MarkdownStyle where the "font" attribute is a getter instead a variable:

struct GenericMarkdownStyle: MarkdownStyle {
    var font: MarkdownStyle.Font { .system(.body) }
    var foregroundColor: MarkdownStyle.Color { .label }
    var codeFontName: String? { nil }
    var codeFontSizeMultiple: CGFloat { 0.94 }
    var headingFontSizeMultiples: [CGFloat] { [2, 1.5, 1.17, 1, 0.83, 0.67] }
}