James Sumners
James Sumners

Reputation: 14777

Store previously selected segment of a UISegmentedControl?

I need to keep track of the previously selected segment of a UISegmentControl. Is there a delegate method I could use? Maybe something like selectedSegmentShouldChange:? The only delegate method I have been able to find is segmentedControl:selectedSegmentChanged:. This delegate is one step after the one I need.

Upvotes: 2

Views: 680

Answers (1)

James Sumners
James Sumners

Reputation: 14777

There is not an API for handling this situation. I instead had to work with a simple FIFO buffer to keep track of the last selected segment. Here is the code for my PreviousItem object:

// PreviousItem.h

#import <Foundation/Foundation.h>

typedef struct {
  char current;
  int a;
  int b;
} itemFIFO;

@interface PreviousItem NSObject {
  itemFIFO stack;
}

- (void) push(int) a;
- (int) pop;

@end

// PreviousItem.m

#import "PreviousItem.h"


@implementation PreviousItem

- (id) init
{
  if ( ![super init] ) {
    return nil;
  }

  stack.a = -1;
  stack.b = -1;

  return self;
}

- (void) push(int) a
{       
  stack.b = stack.a;
  stack.a = a;
}

- (int) pop
{
  return stack.b;
}

@end

An example of it's usage:

prevSegment = [[PreviousItem alloc] init];
[prevSegment push:0]; // Previously selected segment is 0
[mySegmentControl setSelectedSegment:1]; // Choose a new segment
[prevSegment push:1]; // Update our segment stack
// User does something and we need to know the previously selected segment
int oldSegment = [prevSegment pop]; // Will return 0 in this contrived example

Upvotes: 2

Related Questions