gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 05:30:50 30 4
gpt4 key购买 nike

这是我用 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com