Does anybody know of a way to customize the appearance of the string based UISegmentedControl? I am trying to set the background color of the cell and the text color differe
Swift 5.0
if #available(iOS 13.0, *) {
// For selected segment
control.selectedSegmentTintColor = UIColor.red
}
// For control's background
control.layer.backgroundColor = UIColor.black.cgColor
Xcode 11
Select the control and multiple color options are now available. If you need further refinement - check out User Defined Runtime Attributes.
The best way I have found of doing something like this is setting different attributes for different UIControlStates on the segmented control.
self.segmentedControl.tintColor = [UIColor cb_Grey1Color];
self.segmentedControl.backgroundColor = [UIColor cb_Grey3Color];
NSDictionary *selectedAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont cbGothamBookFontWithSize:13.0], NSFontAttributeName,
[UIColor whiteColor], NSForegroundColorAttributeName,
[UIColor cb_Grey1Color], NSBackgroundColorAttributeName, nil];
[self.segmentedControl setTitleTextAttributes:selectedAttributes forState:UIControlStateSelected];
NSDictionary *unselectedAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont cbGothamBookFontWithSize:13.0], NSFontAttributeName,
[UIColor cb_Grey2Color], NSForegroundColorAttributeName,
[UIColor cb_Grey3Color], NSBackgroundColorAttributeName, nil];
[self.segmentedControl setTitleTextAttributes:unselectedAttributes forState:UIControlStateNormal];
Here is a sample code that works with iOS9, but it is a hack, and might not work in later versions:
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"Title1", @"Title2"]];
for (id segment in [segmentedControl subviews])
{
for (id view in [segment subviews])
{
NSString *desc = [view description];
if ([desc containsString:@"UISegmentLabel"])
{
[segment setTintColor:([desc containsString:@"Title1"] ? [UIColor blueColor] : [UIColor greenColor])];
}
}
}
As of iOS13, you would be no longer able to modify the tint color of the segment controller. Need to use selectedSegmentTintColor if the color has to be customised. self.yourSegmentControl.selectedSegmentTintColor = UIColor(red: 240.0/255.0, green: 183.0/255.0, blue: 0.0/255.0, alpha: 1.0)
Font Color swift 3 and swift 4 if you want to change
For Unselected item
segcntrl.setTitleTextAttributes(titleTextAttributes, for: .normal)
For Selected item
segcntrl.setTitleTextAttributes(titleTextAttributes, for: .selected)
//MARK:- Segment color change
self.segc.setTitleTextAttributes([NSAttributedStringKey.foregroundColor:
UIColor.white], for: UIControlState.selected)
self.segc.setTitleTextAttributes([NSAttributedStringKey.foregroundColor:
UIColor.white], for: UIControlState.normal)