danielsaidi / RichTextKit

RichTextKit is a Swift SDK that helps you use rich text in Swift and SwiftUI.
MIT License
814 stars 97 forks source link

Dynamic font resizing according to parent view. #169

Open alelordelo opened 2 months ago

alelordelo commented 2 months ago

Would be great to have dynamic font resizing according to parent view.

This tutorial explains how to achieve this in SwiftUI: https://malauch.com/posts/auto-resizable-text-size-in-swiftui/

I believe in AppKit, this could be used si we can se a adjustFontSizeToFit config option .

@danielsaidi , what you think?

import Cocoa

class DynamicTextView: NSTextView {
    override func viewDidEndLiveResize() {
        super.viewDidEndLiveResize()
        adjustFontSizeToFit()
    }

    private func adjustFontSizeToFit() {
        guard let textStorage = self.textStorage else { return }

        let containerSize = self.textContainer?.size ?? NSSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude)
        var currentFontSize = self.font?.pointSize ?? NSFont.systemFontSize
        let text = textStorage.string

        let textAttributes: [NSAttributedString.Key: Any] = [.font: NSFont.systemFont(ofSize: currentFontSize)]
        var textSize = text.size(withAttributes: textAttributes)

        // Decrease font size if text exceeds the container
        while textSize.width > containerSize.width || textSize.height > containerSize.height {
            currentFontSize -= 1
            textSize = text.size(withAttributes: [.font: NSFont.systemFont(ofSize: currentFontSize)])
        }

        // Apply the adjusted font size
        self.font = NSFont.systemFont(ofSize: currentFontSize)
    }
}
danielsaidi commented 2 months ago

Hi @alelordelo

I'm not sure how this would work with the text view. If you can create an example, I'd be very interested in taking a look at it.