2017-02-23 141 views
11

这是我UISegmentedControl写在斯威夫特:当用户在Swift中选择UISegmentedControl时,如何更改它的样式?

enter image description here

我用下面的代码创建它:

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! 
    } 
} 

但有一件事是错误的。

当我点击(并按住)ONETWO它改变了背景色为这个(为它被用户的手指触摸时):

enter image description here

我错过了一些代码更改UISegmentedControl中选定(临时按下)选项的样式。

我该如何去除暗灰色的选择并使其保持清晰的颜色?

回答

9

如何您已经设置背景图片为UIControlState.normal类似,您需要为UIControlState.highlightedUIControlState.selected + UIControlState.highlighted设置适当的图像。

下面的代码添加到您的扩展功能removeBorders()(假设你想为按未选择段中的清晰的背景和压制选定一个色调彩色背景):

setBackgroundImage(imageWithColor(color: .clear), for: .highlighted, barMetrics: .default) 
setBackgroundImage(imageWithColor(color: tintColor!), for: [.selected, .highlighted], barMetrics: .default) 
+0

我试过了,它几乎工作:)现在当用户按下当前没有选择的选项 - 它不会突出显示为灰色,但是 - 仍然有可能按下当前选中的选项并将背景更改为灰色 - 您知道我该如何修复它? – user3766930

+1

@ user3766930当然,你可以做到,我更新了答案。 –

0
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) 
相关问题