Ios 仅更改swift中选定段的着色颜色

Ios 仅更改swift中选定段的着色颜色,ios,swift,uisegmentedcontrol,Ios,Swift,Uisegmentedcontrol,我正在用objective-c的swift重新做我的一个项目,我在objective-c中使用的一个函数无法正确翻译 这是Objective-C代码 - (void)segmentAction:(UISegmentedControl *)sender { NSLog(@"Segment"); for (int e=0; e<[sender.subviews count]; e++) { if ([[sender.subviews objectAtIndex

我正在用objective-c的swift重新做我的一个项目,我在objective-c中使用的一个函数无法正确翻译

这是Objective-C代码

- (void)segmentAction:(UISegmentedControl *)sender
{
    NSLog(@"Segment");

    for (int e=0; e<[sender.subviews count]; e++) {
        if ([[sender.subviews objectAtIndex:e]isSelected]) {

            [[sender.subviews objectAtIndex:e] setTintColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"gradient.png"]]];
        } else {
            [[sender.subviews objectAtIndex:e] setTintColor:nil];
        }
    }
}
-(void)分段操作:(UISegmentedControl*)发送方
{
NSLog(@“段”);

for(int e=0;e
子视图
是任意对象的数组,因此您需要将每个项目强制转换为UIControl,然后才能引用其
选定的
属性:

for item in control.subviews {
    if let subview = item as? UIControl {
        if subview.selected {
            ...
        }
    }
}
编辑:这可以编译,但在运行时不起作用。在iOS 8中,控件的子视图似乎是一个私有UISegment类的实例,它实际上是UIImageView的子类。尝试将每个项目强制转换为UIControl将以静默方式失败。我没有做您正在尝试的事情,因此不确定为什么在iOS 7中会起作用。或者苹果有已更改UISegmentedControl的构建方式,或者UIImageView有一个私有的选定属性。我建议您以其他方式实现此效果,这可能意味着构建分段控件的自定义版本。如果确实要继续使用内部子视图,请将“UIControl”更改为“UIImageView”,然后更改“if subview.selected…”到“if subview.highlighted…”。请记住,这可能在iOS 7上不起作用,并且可能在iOS的更高版本中再次中断。

请尝试下面的代码

let sortedViews = segmentedControl.subviews.sort( { $0.frame.origin.x < $1.frame.origin.x } )
        for (index, view) in sortedViews.enumerate() {
            if index == segmentedControl.selectedSegmentIndex {
                view.tintColor = UIColor(red: 17/255, green: 125/255, blue: 185/255, alpha: 1)
            } else {
                view.tintColor = UIColor.blackColor()
            }
        }
let sortedView=segmentedControl.subview.sort({$0.frame.origin.x<$1.frame.origin.x})
对于SortedView.enumerate()中的(索引、视图){
如果索引==segmentedControl.selectedSegmentIndex{
view.tintColor=UIColor(红色:17/255,绿色:125/255,蓝色:185/255,alpha:1)
}否则{
view.tintColor=UIColor.blackColor()
}
}

这对我有用。试试这个:)

要使选择指示器颜色与框颜色相同,请执行以下操作

    self.segmentcontrol.selectionIndicatorColor = UIColor.blue

swift 5的更新版本 让sortedViews=sender.subviews.sorted(按:{$0.frame.origin.x<$1.frame.origin.x})


subview.selected不是meMy fault的选项-selected是UIControl上的属性,不是UIView。我已经更新了我的答案。我遇到了问题,我把它放在哪里?它不会通过if let subview行,因为我的回答不适合作为注释,所以我将它添加到了答案下面。
    self.segmentcontrol.selectionStyle = .box;
    self.segmentcontrol.selectionIndicatorBoxColor = UIColor.blue
    self.segmentcontrol.selectionIndicatorColor = UIColor.blue
    for (index, view) in sortedViews.enumerated() {
        if index == sender.selectedSegmentIndex {
            view.tintColor = UIColor.blue //UIColor.blueColor()
        } else {
            view.tintColor = UIColor.white
        }
    }