这是我UISegmentedControl
写在斯威夫特:当用户在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
中选定(临时按下)选项的样式。
我该如何去除暗灰色的选择并使其保持清晰的颜色?
我试过了,它几乎工作:)现在当用户按下当前没有选择的选项 - 它不会突出显示为灰色,但是 - 仍然有可能按下当前选中的选项并将背景更改为灰色 - 您知道我该如何修复它? – user3766930
@ user3766930当然,你可以做到,我更新了答案。 –