Equal sized cells in NSSegmentedControl

355 Views Asked by At

For my NSSegmentedControl, I use it do display a bar to control a NSTableView. I have code set up to control the size programmatically:

for (NSInteger i = 1; i <= numberOfSegments; i++) {
         
        CGSize textSize = [[NSString stringWithFormat:@"Workspace %ld", (long)i] sizeWithAttributes:@{NSFontAttributeName: [NSFont systemFontOfSize:13.0f]}];
        
        NSInteger segmentWidth = self.workspaceControl.frame.size.width / numberOfSegments;
        
        if (textSize.width > segmentWidth) {
            [self.workspaceControl setLabel:[NSString stringWithFormat:@"%ld", (long)i] forSegment:i - 1];
        } else {
            [self.workspaceControl setLabel:[NSString stringWithFormat:@"Workspace %ld", (long)i] forSegment:i - 1];
        }
        
        [self.workspaceControl setWidth:segmentWidth forSegment:i - 1];
        
    }

This works, by a small problem occurs.

At the beginning (with one segment) it looks like this:

before modification

As I change the value, the right side gets clipped slightly.

4 segments

10 segments

And then back to one segment:

back to one segment

The constraints are as follows:

constraints

Im very puzzled by the clipping (probably because a couple pixels t0o large), but I have no idea how to fix it, or is there a better way to get evenly spaced cells?

1

There are 1 best solutions below

0
On

In my testing the generated width constraints of the NSSegmentedControl segments appear to round to whole numbers despite setWidth(_ width: CGFloat, forSegment segment: Int) taking a CGFloat. Thus the total width of the segments can add up to more than the width of the control itself.

To get even segments pass segmentWidth through the floor. Also, set a manual width for the control and constrain it horizontally by the centerXAnchor instead of by the leading and trailing anchors to preserve its center-alignment.

Drawbacks: the width must be hard-coded and the left and right margins may not match your other views exactly.