应用程序全屏时如何调整文本大小

问题描述

我在 swift 中创建了一个标签 (TextField),当我的 macOS 应用程序进入全屏时,它会调整大小。 但是文本字段内的文本仍然具有相同的大小。它没有调整大小。 如何根据屏幕大小或文本框大小调整文本大小? 请帮我解决这个问题。

解决方法

要检测全屏更改,请在视图控制器的 viewDidLoad 中添加观察者:

NotificationCenter.default.addObserver(self,selector: #selector(didEnterFullscreen),name: NSWindow.didEnterFullScreenNotification,object: self.view.window)
NotificationCenter.default.addObserver(self,selector: #selector(didExitFullscreen),name: NSWindow.didExitFullScreenNotification,object: self.view.window)

然后在 fontdidEnterFullscreen 中设置文本字段的 didExitFullscreen 属性。

然而,一个更通用的解决方案是在文本字段改变大小时更新字体:

class AutoResizableTextField: NSTextField {
    
    override var frame: NSRect {
        didSet {
            // Find the max font size that does not cause the text to exceed our frame
            var font = self.font?.withSize(1) ?? NSFont.systemFont(ofSize: 1)
            var string = attributedStringValue
            // Increase font size until the text just barely fits
            while true {
                font = font.withSize(font.pointSize + 1)
                // Calculate the size of the text with this font
                let next = NSMutableAttributedString(attributedString: string)
                next.addAttribute(.font,value: font,range: NSRange(location: 0,length: string.length))
                var size = next.size()
                // Pad the size a bit to prevent clipping
                size.width += 6
                size.height += 6
                if size.width > frame.width || size.height > frame.height { break }
                string = next
            }
            // Set the font
            attributedStringValue = string
        }
    }
}

只要确保设置 textField.autoresizingMask = [.width,.height] 以在窗口调整大小时让字段调整大小。