为MacOS App在NSTextFieldCell(Swift 3)中自动调整文本

时间:2016-10-12 21:07:52

标签: swift xcode nstextfield nstextfieldcell

我的问题:我正在Swift 3中构建一个MacOS应用,我希望在NSTextFieldCell中自动调整大小(更改字体大小)文本,这样文本总是如此在容器中可见。

我遇到了Get NSTextField contents to scale,但我不确定如何在我的应用中将此应用于Swift 3。有没有人对如何实现我的目标有任何建议或解释(甚至链接)?

1 个答案:

答案 0 :(得分:2)

我已经创建了一个返回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)

告诉我这是否适合你