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

标签 ios swift swift3 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 中选定(临时按下)选项样式的代码。

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

最佳答案

与您已经为 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)

关于ios - 当用户在 Swift 中选择 UISegmentedControl 时,如何更改它的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42425629/

相关文章:

ios - 获取 CGFloat 最接近的值

用于 RSS 提要解析的 Objective-C 库?

swift - +/- 购物车 View Controller 中的产品数量,每个按钮都位于 TableViewCell 上,它从数组中获取默认数量作为整数

ios - 图片从 iOS Swift 上传到 Node.js 和 Express 后端

swift - 追踪 Swift 中过多的保留/释放

ios - 如何更改 textView 中预选单词的样式?

ios - swift 3 : Add UIButton extension to ViewController

ios - 导航栏错误

ios - 未调用 Swift 3 委托(delegate)函数

ios - 如何将sps pps(从mp4文件读取)信息添加到每个IDR帧