没有简单而明显的方法可以做到这一点,但就像 AppKit 中的许多事情一样,一旦你弄清楚你需要子类化什么就不会太难了。我遇到了this example by Hem Dutt,在我对 macOS 10.12 的测试中,这种方法似乎效果很好。简而言之,您只需要继承NSTextFieldCell 并重写一些方法来更改文本框架。这是 Swift 3 的一个变体:
class CustomTextFieldCell: NSTextFieldCell {
private static let padding = CGSize(width: 4.0, height: 2.0)
override func cellSize(forBounds rect: NSRect) -> NSSize {
var size = super.cellSize(forBounds: rect)
size.height += (CustomTextFieldCell.padding.height * 2)
return size
}
override func titleRect(forBounds rect: NSRect) -> NSRect {
return rect.insetBy(dx: CustomTextFieldCell.padding.width, dy: CustomTextFieldCell.padding.height)
}
override func edit(withFrame rect: NSRect, in controlView: NSView, editor textObj: NSText, delegate: Any?, event: NSEvent?) {
let insetRect = rect.insetBy(dx: CustomTextFieldCell.padding.width, dy: CustomTextFieldCell.padding.height)
super.edit(withFrame: insetRect, in: controlView, editor: textObj, delegate: delegate, event: event)
}
override func select(withFrame rect: NSRect, in controlView: NSView, editor textObj: NSText, delegate: Any?, start selStart: Int, length selLength: Int) {
let insetRect = rect.insetBy(dx: CustomTextFieldCell.padding.width, dy: CustomTextFieldCell.padding.height)
super.select(withFrame: insetRect, in: controlView, editor: textObj, delegate: delegate, start: selStart, length: selLength)
}
override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) {
let insetRect = cellFrame.insetBy(dx: CustomTextFieldCell.padding.width, dy: CustomTextFieldCell.padding.height)
super.drawInterior(withFrame: insetRect, in: controlView)
}
}
我对原始版本进行了一项显着更改——覆盖 cellSize(forBounds:) 以增加单元格的最小高度。我正在使用自动布局来自动调整单元格的大小,所以如果没有覆盖,我的文本就会被剪裁。