2016-10-06 3 views
2

NSTextFieldの余白またはパディングを設定する可能性があるのでしょうか?NSTextFieldマージンと埋め込み? (スウィフト)

私はこのコードを使用して...

enter image description here

...多かれ少なかれカスタム探してテキストフィールド(このスクリーンショットで最初の1)を達成した:

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) 

しかし、それを数字が境界線に近すぎないように、左側にパディングを追加する必要があるように感じます。それも可能ですか?

+0

センターで調整してみませんか? – Do2

答えて

2

私は通常、テキストフィールドをコンテナビューに配置するだけでこれを行います。ビューに任意のコーナー半径、境界線などを指定して、必要なすべてのパディングを使用してtextFieldを内側に拘束するだけです。 textFieldのボーダースタイルを 'none'に変更することをお勧めします。そうしないと、視野の中で見ることができません。

ボタンでできるようにコンテンツを挿入する方法があるかもしれませんが、それを見つけることはできませんでした。

+1

このソリューションの問題点は、textFieldが選択されている場合、強調表示された境界線がコンテナビューの境界線と一致しないことです。 – ixany

+0

はい、そうです。あなたはパディングのことがきれいな方法でサポートされていないように、最終的にはあなたにとって何が重要かを選択する必要があります。 – creeperspeak

0

これを行うには単純で明白な方法はありませんが、AppKitの多くの機能と同様に、サブクラス化する必要があるものを正確に把握することは難しくありません。私は​​に遭遇し、macOS 10.12に関する私のテストでは、このアプローチはうまくいくようです。つまり、NSTextFieldCellをサブクラス化して、テキストフレームを変更するためのいくつかのメソッドをオーバーライドするだけです。ここでスウィフト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つの顕著な変更を行いました。オートレイアウトを使用してセルのサイズを自動的に調整しています。オーバーライドしないと、テキストがクリップされていました。