Reputation: 1201
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:
As I change the value, the right side gets clipped slightly.
And then back to one segment:
The constraints are as follows:
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?
Upvotes: 3
Views: 364
Reputation: 101
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.
Upvotes: 1