这是我的UISegmentedControl写在
Swift:
我用以下代码创建了它:
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)