【问题标题】:UISegmentedControl Borders/Highlighted StateUISegmentedControl 边框/高亮状态
【发布时间】:2017-05-21 17:06:09
【问题描述】:

我目前在我的 VC 中有一个 uisegmentedcontrol 元素,并通过遵循下面的线程设法删除了边框。虽然它工作正常,但一旦选择 uisegmentedcontrol 部分变成全白,包括图标,有没有办法修改它?因此,所选部分的背景将是我指定的任何颜色,并且图标变为白色。提前感谢任何可能提供帮助的人。

提到的线程: Swift: How to remove border from segmented control

【问题讨论】:

  • 能分享一下SegmentedControl的代码和截图吗?
  • 我添加了一个截图,选择了第二部分,代码请访问我发布的链接,答案是我正在使用的确切代码
  • 我认为你可以使用选中和未选中状态来使用不同的颜色
  • 我已经在代码中使用 .isHighlighted 方法尝试过,但没有。有没有其他方法可以无边框并保留所选颜色?
  • 请分享代码。

标签: ios swift xcode uisegmentedcontrol


【解决方案1】:

这是您可以更改UISegmentControl 中选定指标的背景颜色的方法

extension UISegmentedControl{
    func removeBorders() {
        setBackgroundImage(imageWithColor(color: .clear), for: .normal, barMetrics: .default)
        setBackgroundImage(imageWithColor(color: .gray), 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!
    }
}

正如您在removeBorders 函数中看到的,您正在为normalselected 状态设置基于颜色的背景图像。所以在这里你可以使用任何你喜欢的颜色。

【讨论】:

  • 非常感谢!我一回到我的电脑就试一试,再次感谢!
  • 感谢我的荣幸 :)
猜你喜欢
  • 1970-01-01
  • 2019-03-08
  • 2011-11-29
  • 1970-01-01
  • 1970-01-01
  • 2013-12-06
  • 2010-10-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多