简体   繁体   中英

cocoa - add NSTextfield to NSRect

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM