Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamic font resizing according to parent view. #169

Open
alelordelo opened this issue Apr 23, 2024 · 1 comment
Open

Dynamic font resizing according to parent view. #169

alelordelo opened this issue Apr 23, 2024 · 1 comment
Labels
feature New feature or request

Comments

@alelordelo
Copy link

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
Copy link
Owner

danielsaidi commented Apr 23, 2024

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.

@danielsaidi danielsaidi added the feature New feature or request label Apr 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants