I'm sorry to ask such a question, but I can't seem to find the answer for it from the wild web.
I want to find out the location of a NSTextField
in my custom view, so I can add other textfields under it programmatically.
The reason I don't just add other textfields in IB, is because I need to be able to dynamically create them.
The NSTextF开发者_如何学Goield
is linked to an IBOutlet
.
So the main question is: How do I find out the location of a NSTextField
(or NSButton
, it doesn't really matter atm) in a custom view (I need to get the coordinates of the item)?
Make an instance Variable with the NSTextField and then call these methods on it to get the four values you want.
NSRect textFieldFrame = [textField frame];
NSPoint textFieldLocation = textFieldFrame.origin;
NSSize textFieldSize = textFieldFrame.size;
NSInteger x = textFieldLocation.x;
NSInteger y = textFieldLocation.y;
NSInteger width = textFieldSize.width;
NSInteger height = textFieldSize.height;
Every kind of view or control (like NSButton
, NSTextField
, etc.) that inherits from NSView
has a -frame
method that contains the positioning information.
If your custom view has an IBOutlet
connected up to the NSTextField
, you could do the following:
NSRect textFieldFrame = [textField frame];
That NSRect
contains all of the information for where the text field is positioned.
See the following 2 guides for more information:
View Programming Guide: Understanding a View's Frame and Bounds
Cocoa Drawing Guide: Coordinate Systems and Transforms
Any view has both a bounds
and a frame
property. bounds
is the rectangle that encloses the view in that view's own coordinate space; frame
is the enclosing rectangle in the superview's coordinate space. In this case, you want the text view's frame, i.e. its location and size in the view that contains it, so that you can locate other text views in the same superview.
精彩评论