问题
In Swift
, how do I change the tint opacity of the selected index, but not the border of the whole control?
This changes the color and opacity of the whole control:
sessionTypeSegmentedControl.tintColor = UIColor(red: 140/255, green: 140/255, blue: 140/255, alpha: 0.1)
Followed by this I tried:
sessionTypeSegmentedControl.layer.borderColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).cgColor
But this has no effect on the border.
EDIT:
I want to change the blue background color opacity shown in this image. On the far left.
http://i.stack.imgur.com/GgUwN.png
So the expected result would be:
http://imgur.com/a/AIRhO
回答1:
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
}
回答2:
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];
}
}
}
来源:https://stackoverflow.com/questions/39912451/segmented-control-change-tint-opacity-but-not-border