Search code examples
xcodecocoaxcode4.2vertical-alignmentnstextfield

NSTextField Vertical alignment


I am creating cocoa app in which i created NSTextField programmatically like this,

NSView *superView = [[NSView alloc] initWithFrame:NSMakeRect(0, 300, 1400, 500)];
NSTextField *myTextField = [[NSTextField alloc] initWithFrame:NSMakeRect(180, 100, 1000, 300)];
[myTextField setStringValue:myText];
[myTextField setEditable:NO];
[myTextField setBezeled:NO];
[myTextField setDrawsBackground:NO];
[myTextField setSelectable:NO];
[myTextField setFont:[NSFont fontWithName:@"Futura" size:22]];
[superView addSubview:myTextField];
[superView setAutoresizesSubviews:YES];
[myTextField setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[self.window.contentView addSubview:superView];  

Now i want vertical alignment of my text and it should be adjustable according to text length.
Anyone have any suggestions? Please share your suggestion :)

Many Thanks..!!


Solution

  • What you want is possible, but you'll have to make a subclass of NSTextFieldCell, and then use that subclass in your NSTextField. The key methods you want override are drawingRectForBounds:, selectWithFrame:, and editWithFrame:

    Here is a blog post from the fantastic Daniel Jalkut about this, he even includes a downloadable version ready to go. The post is fairly old but it should still work fine.