Segmented control, change tint opacity, but not border

拟墨画扇 提交于 2019-12-06 16:23:10

I found this solution... Swift 3 Xcode 8

    @IBAction func valueChanged(_ sender: UISegmentedControl) {

    for (index,element) in segment.subviews.enumerated() {

        if index != sender.selectedSegmentIndex {
            element.tintColor = UIColor.red
            element.alpha = 0.5
        }else {

            element.tintColor = UIColor.red
            element.alpha = 1

        }
    }



}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    for (index,element) in segment.subviews.enumerated() {

        if index != segment.selectedSegmentIndex {
            element.tintColor = UIColor.red
            element.alpha = 0.5
        }else {

            element.tintColor = UIColor.red
            element.alpha = 1

        }
    }

            segment.layer.cornerRadius = 5
            segment.layer.borderColor = UIColor.black.cgColor
            segment.layer.borderWidth = 1
            segment.clipsToBounds = true



}

This code worked for me.

Swift3 Sample Code

override func viewDidLoad() {
    super.viewDidLoad()
    segmentedControl.tintColor = UIColor.black
    segmentedControl.layer.cornerRadius = 5
    segmentedControl.clipsToBounds = true
    segmentedControl.layer.borderColor = UIColor.black.cgColor
    segmentedControl.layer.borderWidth = 1
}

@IBAction func valueChanged(_ sender: UISegmentedControl) {
    for indx in 0 ... sender.subviews.count-1 {
        let subview = sender.subviews[indx]
        if indx != sender.selectedSegmentIndex {
            subview.tintColor = UIColor.red.withAlphaComponent(0.5)
            subview.backgroundColor = UIColor.red.withAlphaComponent(0.5)
        } else {
            subview.tintColor = nil
            subview.backgroundColor = nil
        }
    }
}

Here is the code, I use to use in Obj-C, but I cannot figure out (yet) how to call isSelected on subview in Swift3.

Objective-C

-(void)valueChanged {
    for (int i=0; i<[self.subviews count]; i++)
    {
        if ([[self.subviews objectAtIndex:i] respondsToSelector:@selector(isSelected)] && [[self.subviews objectAtIndex:i]isSelected])
        {
            [[self.subviews objectAtIndex:i] setTintColor:ORANGE_COLOR];
            [[self.subviews objectAtIndex:i] setBackgroundColor:ORANGE_COLOR];

        }
        if ([[self.subviews objectAtIndex:i] respondsToSelector:@selector(isSelected)] && ![[self.subviews objectAtIndex:i] isSelected])
        {
            [[self.subviews objectAtIndex:i] setTintColor:LIGHT_BLUE_COLOR];
            [[self.subviews objectAtIndex:i] setBackgroundColor:LIGHT_BLUE_COLOR];

        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!