McDonal_11 McDonal_11 - 15 days ago 5
Swift Question

Swift: Background color change in selected segment of UISegmentControl

In my Swift app, I dont know how to change BGColor for selected segment alone, in UISegmentControl. I have tried a lot, only tint color is changing. I got success in Objective - C. I dont know how to convert that to SWIFT. Kindly guide me. My codings below:

Objective C

- (IBAction)mySeg:(UISegmentedControl *)sender {

for (int i=0; i<[sender.subviews count]; i++)
{
if ([[sender.subviews objectAtIndex:i]isSelected] )
{
UIColor *tintcolor=[UIColor colorWithRed:255.0/255.0 green:0/255.0 blue:0/255.0 alpha:1.0];
[[sender.subviews objectAtIndex:i] setTintColor:tintcolor]; //HERE SELECTED SEGMENT COLOR ALONE CHANGING
}
else
{
[[sender.subviews objectAtIndex:i] setTintColor:nil];
}
}
}


Swift

@IBAction func mySegAcn(sender: UISegmentedControl) {
for(var i : Int = 0; i < sender.subviews.count; i++)
{
if((sender.subviews[i].isSelected) != nil)
{
//var tint_Color = UIColor(red: 1.0, green: 0, blue: 0, alpha: 1.0)

(sender.subviews[i] as! UIView).tintColor = UIColor .redColor() //HERE WHOLE TINT COLOR IS CHANGING
}

else
{

(sender.subviews[i] as! UIView).tintColor = nil
}
}
}


Output

enter image description here

Answer

The issue with the Swift code is the treatment of the optional: (sender.subviews[i].isSelected) != nil will be true even if isSelected is false.

Try writing your loop using the Swift syntax

for subview in (sender.subviews as! [UIView]) {
   if (subview.isSelected) {
       subview.tintColor = UIColor.redColor()
   } 
   else {
       subview.tintColor = nil
   } 
}

At least in that loop you are actually testing whether or not the subview is selected instead of whether or not the view is not nil.