ios
ios

Reputation: 77

how to set color for segments in segemented control for selected state in ios

I'm using segmented control instead of buttons. how to set the background colour for selected segment. am trying to change background color but it color appears all segments.

Upvotes: 0

Views: 803

Answers (2)

user3182143
user3182143

Reputation: 9609

I tried sample one for your question.I set the segment control in XIB.Also I set three titles.I hooked up the segment to ViewController.h with properties and action.

ViewController.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
}
@property (strong, nonatomic) IBOutlet UISegmentedControl *segmentBgColorChange;
- (IBAction)actionChangeBGColor:(id)sender;
@end

ViewController.m

#import "ViewController.h"
@interface ViewController ()
{
}
@end
@implementation ViewController
@synthesize segmentBgColorChange;

// Then in action methods

- (IBAction)actionChangeBGColor:(id)sender
{
  UISegmentedControl *seg = sender;
  for (int i=0; i<[seg.subviews count]; i++) {
    if ([[seg.subviews objectAtIndex:i]isSelected]) {
        UIColor *bgColor = [UIColor redColor];
        [[seg.subviews objectAtIndex:i] setTintColor:bgColor];
    } else {
        [[seg.subviews objectAtIndex:i] setTintColor:nil];
    }
   }
 }

Upvotes: 0

Sanjukta
Sanjukta

Reputation: 1055

If you set the 1st index selected then write this code.

[segmentControl setSelectedSegmentIndex:0];

If you set the background color then write this code

UIColor *selectedColor = [UIColor whiteColor];
   for (UIControl *subview in [segmentControl subviews]) {

        [subview setTintColor:selectedColor];

    }

If you change the tint color and font size then write this code.

NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:12.0f]};
[segmentControl setTitleTextAttributes:attributes
                              forState:UIControlStateNormal];

[segmentControl setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Helvetica-Bold" size:14.0],
                                         NSForegroundColorAttributeName:[UIColor whiteColor]}
                              forState:UIControlStateNormal];
[segmentControl setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Helvetica-Bold" size:14.0],
                                         NSForegroundColorAttributeName:[UIColor redColor]}
                              forState:UIControlStateSelected];

Upvotes: 1

Related Questions