1

I have a NSSegmentedControl in which, upon user's click, some conditions should be met before the action is sent to its target.

Till now i managed to do this, by overriding the -mouseDown event handler and invoking the segmentedControl's [super mouseDown] handler only after successfully checking my conditions. Only one problem. The user doesn't have any visual clue that a segment has been clicked until [super mouseDown] is invoked.

So the question is: is there a way to set an "highlighted" state programmatically (more or less like "setHighlighted" for NSButtons)?

Rob
  • 26,989
  • 16
  • 82
  • 98

2 Answers2

1

You can deselect the clicked segment in the action method. You could detour through an additional action method

- (IBAction)toggleSegments:(id)sender
{
    NSSegmentedControl *segmentedControl = sender;
    NSInteger selectedSegment = segmentedControl.selectedSegment;

    if (! conditionsAreMet) {
        [segmentedControl setSelected:NO forSegment:selectedSegment];

        return;
    }

    [NSApp sendAction:@selector(reallyToggleSegments:) to:nil from:sender];
}
Pierre Bernard
  • 3,148
  • 2
  • 23
  • 31
  • Thank you Pierre. Your solution is better then nothing, but there's still some point. For example, during the test, the segment will be displayed as *selected*, suggesting that the choice has been accepted. I was looking for a way to only *highlight* the segment, not select it. –  Nov 05 '14 at 16:42
1

Instead of not invoking -[NSSegmentedControl mouseDown] when conditions are not met, you need to not invoke -[NSSegmentedCell stopTracking:at:inView:mouseIsUp:].

Here’s an NSSegmentedControl subclass I wrote that uses a delegate to conditionally enable segment selection: https://gist.github.com/michal-tomlein/39171668c580ac0d497d

You’ll see that the segment is highlighted while you hold down the mouse button, but is then unhighlighted and selection remains unchanged if you return NO from the delegate method.

If you use it from Interface Builder, don’t forget to set both the view class (MTSegmentedControl) and the cell class (MTSegmentedCell).

  • Thank you Michal. I'll give your code a try and let you know if it solves my problem. –  Aug 16 '15 at 10:54