NSTextField边距和填充? (迅速)

时间:2016-10-06 21:51:14

标签: swift xcode swift3 padding nstextfield

我想知道是否有可能为NSTextField设置保证金或填充?

我实现了或多或少的自定义textField(此屏幕截图中的第一个)...

enter image description here

...使用此代码:

myTextField.wantsLayer = true
myTextField.layer?.cornerRadius = 2.0
myTextField.layer?.borderWidth = 1.0
myTextField.layer?.borderColor = CGColor(red: 0.69, green: 0.69, blue: 0.69, alpha: 1.0)

但是,感觉我必须在左侧添加一些填充,以使数字不会太靠近边框。这甚至可能吗?

2 个答案:

答案 0 :(得分:3)

没有简单明了的方法可以做到这一点,但是像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:)做了一个显着的改变,以增加细胞的最小高度。我正在使用自动布局自动调整单元格的大小,因此如果没有覆盖,我的文本就会被剪裁。

答案 1 :(得分:2)

我通常只需将textField放在容器视图中即可。您可以为视图提供所需的任何角半径,边界等,然后使用您想要的任何填充将textField约束到内部。只需确保将textField的边框样式更改为“none”,否则您将能够在视图中看到它。

可能有一种方法可以使用按钮更改内容插入,但我从来没有找到它。