在NSTextField上设置单元格

时间:2013-08-15 19:09:13

标签: objective-c cocoa nstextfield nstextfieldcell

我有一个自定义NSTextFieldCell,我想在NSTextField上设置 如果我在IB上设置它可以正常工作。

enter image description here

这让它像这样工作:

enter image description here

但我想以编程方式设置它,我尝试这样的事情:

-(void)awakeFromNib{

    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];

    }  

这是我得到的结果:

enter image description here

出了什么问题?我的代码是坏的还是什么?

2 个答案:

答案 0 :(得分:1)

这是swift中的一个有效解决方案。以上目标C答案不完整,因此对我没有用。

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

如果替换cell属性,则需要重置所有属性。这些是默认值,请尝试设置与您的案例匹配的值。

答案 1 :(得分:0)

试试这种方式,工作正常:

 NSRect theRect = NSRectFromCGRect( NSMakeRect(50, 100, 100, 100));

    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];