如何解决应用程序全屏时如何调整文本大小
我在 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)
然后在 font
和 didEnterFullscreen
中设置文本字段的 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]
以在窗口调整大小时让字段调整大小。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。