Powered By Blogger

Friday, December 7, 2012

how to make custom segmented control?

Hi,
Many of you want to make custom controls in their own projects but sometime they need some guidance or the way to customize those controls. So, here is the way for everyone who wants to make his/her own custom segmented control in iPhone, iPad projects. Please follow the below steps :

Step 1 : Import these two files in your projects . ("CustomsegmentControl.h","CustomsegmentControl.m")

#import <UIKit/UIKit.h>

@interface CustomSegmentControl : UISegmentedControl
{
    UIColor *unselectedColor,*selectedColor;
}
@property (nonatomic,retain) UIColor *unselectedColor,*selectedColor;
-(id)initWithItems:(NSArray *)items unselectedColor:(UIColor*)unselectedColor selectedColor:(UIColor*)selectedColor;
@end


#import "CustomSegmentControl.h"

@interface CustomSegmentControl(private)
-(void)setupInitialMode;
-(void)switchHighlightColors;
@end

@implementation CustomSegmentControl

@synthesize unselectedColor,selectedColor;

-(id)initWithItems:(NSArray *)items unselectedColor:(UIColor*)unselectedColor selectedColor:(UIColor*)selectedColor {
    if (self = [super initWithItems:items])
    {
        // Initialization code
        self.unselectedColor = unselectedColor;
        self.selectedColor = selectedColor;
        [self setInitialMode];
        [self setSelectedSegmentIndex:0];
    }
    return self;
}
- (void)awakeFromNib
{
    self.unselectedColor = [UIColor colorWithWhite:0.7 alpha:1];
    self.selectedColor = self.tintColor;
    [self setInitialMode];
   
    [self setSelectedSegmentIndex:0];
}

-(void)setupInitialMode
{
    [self setBackgroundColor:[UIColor clearColor]];
    [self setSegmentedControlStyle:UISegmentedControlStyleBar];
   
    for( int i = 0; i < [self.subviews count]; i++ )
    {
        [[self.subviews objectAtIndex:i] setTintColor:nil];
        [[self.subviews objectAtIndex:i] setTintColor:unselectedColor];
    }
    [self addTarget:self action:@selector(switchHighlightColors) forControlEvents:UIControlEventValueChanged];
}


-(void)switchHighlightColors
{
    for (id view in self.subviews) {
        if ([view isSelected]) [view setTintColor:selectedColor];
        else [view setTintColor:unselectedColor];
    }
}

- (void)setSelectedSegmentIndex:(NSInteger)selectedSegmentIndex
{
    [super setSelectedSegmentIndex:selectedSegmentIndex];
    [self switchHighlightColors];
}
@end

Step 2 :  Now make your new custom segment control in the class file wherever you want to use that custom control. 

For example : CustomSegmentControl *obj_customsegment;

obj_customsegment = [[CustomSegmentControl alloc]initWithItems:[NSArray arrayWithObjects:@"One",@"Two",nil] unselectedColor:[UIColor blackColor] selectedColor:[UIColor blueColor]];


Now, you can easily use above custom segment control object in your project.

Regards,
Nilesh Prajapati