I have a custom NSTextFieldCell that i want to set on a NSTextField.
If i set it on the IB it works fine.

enter image description here

And this gets it working like this:

enter image description here

But i want to set it programmatically and i try something like this:


    NSRect theRect = NSRectFromCGRect( NSMakeRect(50, 100, 100, 100));
    NSTextField *inputField = [[NSTextField alloc] initWithFrame:theRect];
    DRKHUDTextFieldCell *theC = [[DRKHUDTextFieldCell alloc] initTextCell:@"textfield"];
    [inputField setCell:theC];

    [[_window contentView] addSubview:inputField];


This is the result i get:

enter image description here

What is going wrong? Is my code bad or what?

  • Did you find any solution? – adev Aug 2 '17 at 7:12

Here is a working solution in swift. Above Objective C answer was not complete and hence didn't work for me.

let cell = CustomTextFieldCell(textCell: "")
self.cell = cell
self.isBordered = true
self.backgroundColor = .white
self.isBezeled = true
self.bezelStyle = .squareBezel
self.isEnabled = true
self.isEditable = true
self.isSelectable = true

You need to reset all the properties if you replace cell property. These are default values, try setting your own values matching your case.

  • hey mate, it has been 3 three years, i don't even remember what i was trying to do. Thanks for your time though, it might help someone else. – ozmax Aug 3 '17 at 8:08
  • @ozmax, Thanks. Please accept answer so people know there is a working solution – adev Aug 15 '17 at 6:32
  • @adev It's not a solution, bc now you have to subclass two objects (textfield and its cell) – John Smith Nov 24 '18 at 16:02
  • @JohnSmith, I am not sure if we need to subclass textfield since this has been a while and I don't remember if I was sub-classing that time. I had the same issue as in question and this is what fixed for me. Hence shared it for others benefit. I am hoping this same answer would work for cases where you are using directly NSTextField and somewhere you can set properties like this.(Note: Question was already about setting a subclassed cell, so that part is fine I guess) – adev Nov 26 '18 at 23:35
  • @adev Look, the problem is that even by subclassing nstextfield, you can't set any custom cell, not even a default NSCell(). If you set it at least programmatically, nothing will appear. I've spend a log time on it and the only option is to create a NSTextField in a storyboard or nib file and set the custom cell there – John Smith Nov 27 '18 at 15:13

Try this way, It is working fine:


    NSTextField *inputField = [[NSTextField alloc] initWithFrame:theRect];

    NSTextFieldCell *theC = [[NSTextFieldCell alloc] initTextCell:@"textfield"];

    [inputField setCell:theC];

    [inputField setBordered:YES];

    [inputField setBackgroundColor:[NSColor whiteColor]];

    [inputField setBezeled:YES];

    [inputField setBezelStyle:0];

   [[_window contentView] addSubview:inputField];

Your Answer

