Question

I'm confused as to why the code below isn't working, what I would like to achieve is to have a NSTextfield in a NSRect but I'm not sure if it's possible and if it is how to do it, I tried the code below but it's not working...

NSRect city_label = NSMakeRect(20, 20, 7, 7);

NSTextField *label = [[NSTextField alloc] initWithFrame:city_label];

label.stringValue = @"Contents of NSTextfield";

The NSRect gets drawn in an NSView

Anyone any ideas?

Was it helpful?

Solution

An NSRect is not the sort of entity which could be "drawn in an NSView"--it is not an instance of a subview of NSView. An NSRect is just a C struct describe size (width and height) and origin (x and y).

After initializing your NSTextField with its frame (keep in mind that the origin here is relative to the view to which you will add the text field as a subview), you must add it to the view that you want to have as its superview. Assuming for a moment that we're in a custom subclass of NSViewController, your code just needs this additional line

[self.view addSubview:label];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top