Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTextField Padding on the Left

How do you add padding to the left of the text in a text field cell using swift? Previous answers are only for UITextField or in Objective C. To be clear, this is for an NSTextField.

like image 566
user3225395 Avatar asked Feb 07 '23 15:02

user3225395


1 Answers

Here is an example of someone who has made a custom NSTextFieldCell in Objective C.

Ported to Swift that looks like this:

import Cocoa

class PaddedTextFieldCell: NSTextFieldCell {

    @IBInspectable var leftPadding: CGFloat = 10.0

    override func drawingRect(forBounds rect: NSRect) -> NSRect {
        let rectInset = NSMakeRect(rect.origin.x + leftPadding, rect.origin.y, rect.size.width - leftPadding, rect.size.height)
        return super.drawingRect(forBounds: rectInset)
    }
}

I've added the padding as a @IBInspectable property. That way you can set it as you like in Interface Builder.

Use With Interface Builder

To use your new PaddedTextFieldCell you drag a regular Text Field to your xib file

Normal Text Field Cell

and then change the class of the inner TextFieldCell to be PaddedTextFieldCell

Change TextFieldCell to PaddedTextFieldCell

Success!

The final result

Use From Code

To use the PaddedTextFieldCell from code, you could do something like this (thank you to @Sentry.co for assistance):

class ViewController: NSViewController {

    @IBOutlet weak var textField: NSTextField! {
        didSet {
            let paddedTextField = PaddedTextFieldCell()
            paddedTextField.leftPadding = 40
            textField.cell = paddedTextField
            textField.isBordered = true
            textField.isEditable = true
        }
    }

    ....
}

Hope that helps you.

like image 162
pbodsk Avatar answered Feb 20 '23 11:02

pbodsk