I've created a subclass of NSTabViewItem
so that I can specify a specific width for the tab view item, as demonstrated in this answer. This is working well, however the label for the tab is not horizontally centered, so there is extra padding to the right of the text. How can I center the text within the label bounds, or how could I properly center the text inside a fixed width NSTabViewItem
?
Asked
Active
Viewed 370 times
0
1 Answers
1
You can override "drawLabel:inRect:" function and give the appropriate rect for drawing here. Like
(void)drawLabel:(BOOL)shouldTruncateLabel
inRect:(NSRect)labelRect{
//find your label size
NSDictionary* attr = [NSDictionary dictionaryWithObjectsAndKeys:
self.tabView.font,NSFontAttributeName,
nil];
NSSize labelSize = [self.label sizeWithAttributes:attr];
//modify your labelRect here.....
labelRect.origin.x += floor((labelRect.size.width - labelSize.width)/2)
labelRect.size.width = labelSize.width;
//call super
[super drawWithFrame:shouldTruncateLabel inRect:labelRect];
}

Sheen Vempeny
- 818
- 1
- 5
- 8
-
How can this be used to draw it at the right location? I thought it'd be `labelRect.origin.x = labelRect.size.width / 2 - labelSize.width / 2` but for some reason the first tab's label is displayed at the left of its tab view, the second and third tab's labels are displayed to the left of those. – Jordan H Mar 26 '15 at 20:50
-
It should be labelRect.origin.x += floor(labelRect.size.width - labelSize.width)/2) and labelRect.size.width = labelSize.width – Sheen Vempeny Mar 26 '15 at 21:25
-
Thanks, that almost does the trick! It does center it but for some reason not all of the text fits in the label. For example with text "Results Calc" in a 90 pt width tab item, it cuts off most of the last c, despite the fact the entire text can fit with padding left over. – Jordan H Mar 26 '15 at 22:15
-
It may be because of label size calculation.You have to specify the correct font attributes here "sizeWithAttributes:". – Sheen Vempeny Mar 26 '15 at 22:24
-
That is indeed the problem, using HelveticaNeue point size 14 worked, but is there a way to get the text's font so it's not fixed to that font? – Jordan H Mar 26 '15 at 22:54
-
Yes. you can use NSTabview's font property – Sheen Vempeny Mar 27 '15 at 07:04
-
Oddly enough using the font property it is still cut off a little. Interesting. – Jordan H Mar 27 '15 at 15:17