user4096537
user4096537

Reputation:

NSSegmentedControl programmatically highlight segment

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)?

Upvotes: 1

Views: 1473

Answers (2)

Michal Tomlein
Michal Tomlein

Reputation: 11

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).

Upvotes: 1

Pierre Bernard
Pierre Bernard

Reputation: 3198

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

Upvotes: 1

Related Questions