[英]How to change selected segment tintColor of UISegmentedControl in Swift
[英]how can I change the style for UISegmentedControl when it is selected by the user in Swift?
这是我用Swift编写的UISegmentedControl
:
我用以下代码创建了它:
let selectedAttributes: NSDictionary = [
NSForegroundColorAttributeName: UIColor.black,
NSFontAttributeName: fontForSegmentedControl!
]
let normalAttributes: NSDictionary = [
NSForegroundColorAttributeName: UIColor.gray,
NSFontAttributeName: fontForSegmentedControl!
]
mySegmentedControl.setTitleTextAttributes(selectedAttributes as [NSObject : AnyObject], for: UIControlState.selected)
mySegmentedControl.setTitleTextAttributes(normalAttributes as [NSObject : AnyObject], for: UIControlState.normal)
删除边框的扩展名在这里:
extension UISegmentedControl {
func removeBorders() {
setBackgroundImage(imageWithColor(color: UIColor.white/*backgroundColor!*/), for: .normal, barMetrics: .default)
setBackgroundImage(imageWithColor(color: tintColor!), for: .selected, barMetrics: .default)
setDividerImage(imageWithColor(color: UIColor.clear), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
}
// create a 1x1 image with this color
private func imageWithColor(color: UIColor) -> UIImage {
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor);
context!.fill(rect);
let image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image!
}
}
但是有一件事是错的。
当我点击(并按住) ONE
或TWO
它将背景颜色更改为此(用户手指触摸的时间):
我在UISegmentedControl
缺少一些用于更改所选(临时按下)选项样式的代码。
如何删除深灰色选项并使其保持清晰的颜色?
与您已经为UIControlState.normal
设置背景图像的方式类似,您需要为UIControlState.highlighted
和UIControlState.selected
+ UIControlState.highlighted
设置适当的图像。
将以下代码添加到您的扩展函数removeBorders()
(假设您希望有一个清晰的背景,用于按下未选择的段,并为要按下的选定段提供浅色背景):
setBackgroundImage(imageWithColor(color: .clear), for: .highlighted, barMetrics: .default)
setBackgroundImage(imageWithColor(color: tintColor!), for: [.selected, .highlighted], barMetrics: .default)
let normalAttributes: NSDictionary = [
NSForegroundColorAttributeName: UIColor.gray,
NSFontAttributeName: fontForSegmentedControl!
]
mySegmentedControl.setTitleTextAttributes(selectedAttributes as [NSObject : AnyObject], for: UIControlState.selected)
以上代码仅为选择添加灰色,因此请按以下方式进行更改
let normalAttributes: NSDictionary = [
NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: fontForSegmentedControl!
]
mySegmentedControl.setTitleTextAttributes(selectedAttributes as [NSObject : AnyObject], for: UIControlState.selected)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.