Ios ui分段控制边界/突出显示状态
我目前在我的VC中有一个uisegmentedcontrol元素,并且已经按照下面的线程删除了边框。虽然它工作正常,但一旦选中,uisegmentedcontrol部分(包括图标)将完全变为白色,是否有任何方法可以修改它?因此,所选部分的背景将是我指定的任何颜色,图标将变为白色。提前感谢任何可能提供帮助的人 该线程提到:Ios ui分段控制边界/突出显示状态,ios,swift,xcode,uisegmentedcontrol,Ios,Swift,Xcode,Uisegmentedcontrol,我目前在我的VC中有一个uisegmentedcontrol元素,并且已经按照下面的线程删除了边框。虽然它工作正常,但一旦选中,uisegmentedcontrol部分(包括图标)将完全变为白色,是否有任何方法可以修改它?因此,所选部分的背景将是我指定的任何颜色,图标将变为白色。提前感谢任何可能提供帮助的人 该线程提到: 这是如何更改UISegmentControl extension UISegmentedControl{ func removeBorders() {
这是如何更改
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
功能中看到的,您正在根据normal
和selected
状态的颜色设置背景图像。因此,您可以在此处使用您喜欢的任何颜色。这就是您可以在ui部分控件中更改所选指示器的背景色的方法。
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
功能中看到的,您正在根据normal
和selected
状态的颜色设置背景图像。因此,您可以在这里使用您喜欢的任何颜色。您可以共享代码和SegmentedControl的屏幕截图吗?我添加了一个屏幕截图,其中第2部分已选中,对于代码,请访问我发布的链接,答案就是我正在使用的代码。我认为您可以使用“选定”和“未选定”状态来使用不同的颜色。我已经尝试在代码中使用.ishighlight方法,但什么都没有。有没有其他方法可以让它没有边框并保留选定的颜色?请共享代码。您可以共享代码和SegmentedControl的屏幕截图吗?我已经添加了一个选中第二部分的屏幕截图,对于代码,请访问我发布的链接,答案就是我正在使用的代码。我认为您可以使用“选定”和“未选定”状态来使用不同的颜色。我已经尝试在代码中使用.ishighlight方法,但什么都没有。有没有其他方法可以让它无边框并保留所选颜色?请分享代码。非常感谢!我一回到我的电脑就会给它一个机会,再次感谢!谢谢这是我的荣幸:)非常感谢!我一回到我的电脑就会给它一个机会,再次感谢!谢谢,这是我的荣幸:)