要让NSTextField自动调整字体大小以适合其文本,您可以使用以下方法:
import Cocoa
class AutoFittingTextField: NSTextField {
override func awakeFromNib() {
super.awakeFromNib()
self.isEditable = false
self.isSelectable = false
self.maximumNumberOfLines = 1
}
override func setStringValue(_ string: String) {
super.setStringValue(string)
adjustFontSize()
}
private func adjustFontSize() {
let fontManager = NSFontManager.shared
var fontSize = font?.pointSize ?? 12
while fontManager.traitsOfFont(font!) != [] {
fontSize -= 1
font = fontManager.convert(font!, toSize: fontSize)
}
while fontManager.isMultiple(stringValue, forFont: font!) {
fontSize += 1
font = fontManager.convert(font!, toSize: fontSize)
}
}
}
import Cocoa
class AutoFittingTextField: NSTextField {
override func awakeFromNib() {
super.awakeFromNib()
self.isEditable = false
self.isSelectable = false
self.maximumNumberOfLines = 1
}
override func setStringValue(_ string: String) {
super.setStringValue(string)
adjustFontSize()
}
private func adjustFontSize() {
let layoutManager = NSLayoutManager()
let textStorage = NSTextStorage(string: stringValue, attributes: [.font: font!])
textStorage.addLayoutManager(layoutManager)
var fontSize = font?.pointSize ?? 12
let containerSize = bounds.size
while layoutManager.usedRect(for: textContainer!).size.width > containerSize.width || layoutManager.usedRect(for: textContainer!).size.height > containerSize.height {
fontSize -= 1
font = font?.withSize(fontSize)
textStorage.removeLayoutManager(layoutManager)
textStorage.addLayoutManager(layoutManager)
}
}
}
这些方法可以帮助您自动调整NSTextField的字体大小以适应其文本。您可以根据需要选择合适的方法。
领取专属 10元无门槛券
手把手带您无忧上云