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

use*_*930 11 uisegmentedcontrol ios swift swift3

这是我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)
Run Code Online (Sandbox Code Playgroud)

删除边框的扩展名在这里:

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!
    }
}
Run Code Online (Sandbox Code Playgroud)

但是有一件事是错的.

当我点击(并按住)ONE或者TWO它将背景颜色更改为此时(用户的手指触摸它的时间):

在此输入图像描述

我错过了一些代码来更改所选(临时按下)选项的样式UISegmentedControl.

如何删除深灰色选项并使其保持清晰的颜色?

Art*_*m M 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)
Run Code Online (Sandbox Code Playgroud)