Monday 6 October 2014

How to change UISegmentedControl text font and color

UISegmentedControl is mainly used to toggle between two screen or functionality from a common screen. but some times it requires to change the font size of the UISegmentedControl text. Interface builder is not providing the option to change the text font size.

Let me share the way how to change UISegmentedControl text font size and text color.

Create a new viewcontroller in your project or may create a new project if you dont want to modify your existing project for safety point of view.

I am creating UIsegmented control using code but if you using IBOutlet you can go with that also.

in .h file

@interface ViewController : UIViewController

@property (strong, nonatomic)  UISegmentedControl *segment1;

@property (strong, nonatomic)  UISegmentedControl *segment2;
@end

in .m file

 - (void)viewDidLoad
{
    [super viewDidLoad];
   
     NSMutableArray *segtitleArr=[[NSMutableArray alloc]initWithObjects:@"First1",@"Second2", nil];
    _segment1 = [[UISegmentedControl alloc]initWithItems:segtitleArr];
    _segment1.frame = CGRectMake(30, 50, 252, 29);
   
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                [UIFont fontWithName:@"Helvetica" size:17], NSFontAttributeName,
                                [UIColor redColor], NSForegroundColorAttributeName, nil];

  
    [_segment setTitleTextAttributes:attributes forState:UIControlStateNormal];
  
    [self.view addSubview:_segment];



//creating second segment.
  
    NSMutableArray *segtitleArr2=[[NSMutableArray alloc]initWithObjects:@"Third3",@"Fourth"4, nil];
    _segment2 = [[UISegmentedControl alloc]initWithItems:segtitleArr2];
    _segment2.frame = CGRectMake(30, 152, 252, 29);
    _segment2.tintColor = [UIColor colorWithRed: 8/255.0 green:83/255.0 blue:131/255.0 alpha:1.0];
  
    NSDictionary *attributes2 = [NSDictionary dictionaryWithObjectsAndKeys:
                                [UIFont fontWithName:@"Helvetica" size:10], NSFontAttributeName,
                                [UIColor orangeColor], NSForegroundColorAttributeName, nil];

  
    [_segment2 setTitleTextAttributes:attributes2 forState:UIControlStateNormal];
  
    [self.view addSubview:_segment2];




Best way to change UISegmentedControl text colr and  size



Above code will show you two segment control in different text size and font color and selected segmented color change using tint color property.
In both UISegmented control one thing is common that is a NSDictionary having objects of Font/Text and color these you can change as per your requirement.

If you find another best way to change UISegmentedControl  text  size and color, Please share using your comments below.

 

  
}

No comments:

Post a Comment