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.
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.
To use your new PaddedTextFieldCell
you drag a regular Text Field
to your xib file
and then change the class of the inner TextFieldCell
to be PaddedTextFieldCell
Success!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With