当用户在 Swift 中选择 UISegmentedControl 时,如何更改它的样式?

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

但是有一点不对劲。

当我点击(并按住)ONETWO 时,它会将背景颜色更改为此(当它被用户手指触摸时):

我缺少一些用于更改 UISegmentedControl 中选定(临时按下)选项的样式的代码。

如何删除深灰色选区并保留清晰的颜色?

与您已经为 UIControlState.normal 设置背景图片的方式类似,您需要为 UIControlState.highlightedUIControlState.selected + UIControlState.highlighted.[=16 设置合适的图片=]

将以下代码添加到您的扩展函数 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)