我的问题:我正在Swift 3中构建一个MacOS应用程序,并希望在NSTextFieldCell
中自动调整大小(更改font-size)文本,以便文本始终在其容器中可见。
我遇到Get NSTextField内容缩放,但我不确定如何将其应用于我的应用程序中的Swift 3。有人有任何建议或解释(甚至链接)如何实现我的目标?
我创建了一个返回NSFont对象的函数:
func calculateFont(toFit textField: NSTextField, withString string: NSString, minSize min: Int, maxSize max: Int) -> NSFont {
for i in min...max {
var attr: [String: Any] = [:] as Dictionary
attr[NSFontSizeAttribute] = NSFont(name: textField.font!.fontName, size: CGFloat(i))!
let strSize = string.size(withAttributes: [NSFontAttributeName: NSFont.systemFont(ofSize: CGFloat(i))])
let linesNumber = Int(textField.bounds.height/strSize.height)
if strSize.width/CGFloat(linesNumber) > textField.bounds.width {
return (i == min ? NSFont(name: "(textField.font!.fontName)", size: CGFloat(min)) : NSFont(name: "(textField.font!.fontName)", size: CGFloat(i-1)))!
}
}
return NSFont(name: "(textField.font!.fontName)", size: CGFloat(max))!
}
你可以这样使用:
// set multines
self.textField.lineBreakMode = .byWordWrapping // this looks like it doesn't work, set it in the storyboard instead
self.textField.maximumNumberOfLines = 100
// set font
self.textField.font = self.calculateFont(toFit: self.textField, withString: self.textField.stringValue as NSString, minSize: 8, maxSize: 50)
告诉我这是否适合你