macoscocoanstabview

Horizontally center label in NSTabViewItem


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?

enter image description here


Solution

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