0

Is there a way to have an NSTextField without any margins? I'm trying to set my textfield as wide as the text itself, but I have to add some random nr (10px) to make it all show.

NSSize size = [title sizeWithAttributes:[NSDictionary dictionaryWithObject:[NSFont fontWithName:@"LucidaGrande" size:fontSize] forKey:NSFontAttributeName]];

1 Answers1

0

Have you tried just using sizeToFit that NSTextField inherits from NSControl? I tried it in a test project here and it seems to work fine.

For example:

[textField sizeToFit];

[UPDATE]: Perhaps I'm not understanding. Are you programmatically creating the text fields which display the text or something? If so, you can still use sizeToFit to have the text field properly size itself before you add it to the view hierarchy. For example, the following code:

// this code sample assumes ARC
NSTextField *labelField = [[NSTextField alloc] initWithFrame:
                                  NSMakeRect(0.0, 0.0, 10.0, 10.0)];
[[labelField cell] setFont:[NSFont systemFontOfSize:[NSFont systemFontSize]]];
[labelField setBezeled:NO];
[labelField setDrawsBackground:NO];
[labelField setEditable:NO];
[labelField setSelectable:YES];

[labelField setStringValue:@"Sphinx of black quartz, judge my vow. Sphinx of black quartz, judge my vow."];

NSLog(@"labelField.frame (BEFORE) == %@", NSStringFromRect(labelField.frame));
NSLog(@"calling [labelField sizeToFit]");

[labelField sizeToFit];

NSLog(@"labelField.frame (AFTER) == %@", NSStringFromRect(labelField.frame));

labelField.frame = NSOffsetRect(labelField.frame, 50.0, 100.0);

[self.window.contentView addSubview:labelField];

Running this code will produce the following logged output:

2013-02-28 17:23:21 SizeToFit[] labelField.frame (BEFORE) == {{0, 0}, {10, 10}}
2013-02-28 17:23:21 SizeToFit[] calling [labelField sizeToFit]
2013-02-28 17:23:21 SizeToFit[] labelField.frame (AFTER) == {{0, 0}, {493, 17}}

In this code, I created an NSTextField with an arbitrary initial frame size of only 10 pixels by 10 pixels. After setting several properties of the field so that it's equivalent to a standard 13pt label, I then set the string value to a long string which would obviously not fit in only 10 px worth of space. After setting the string value, the logging call shows that the frame of the text field is still the same 10 x 10 dimensions. I then call [labelField sizeToFit], and as you can see, the second logging call shows that the text field has resized itself to be the ideal size. You should be able to use this size in your calculations of where to place the text field.

NSGod
  • 22,699
  • 3
  • 58
  • 66
  • The problem is I'm calculating where to place the string beforehand. The margins are a problem in calculating this correctly. Ideally I just want no margin at all. –  Feb 28 '13 at 20:48