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

时间:2017-02-23 20:31:26

标签: ios swift swift3 uisegmentedcontrol

这是我在Swift中写的SELECT ID, DATE, Status FROM YOUR_TABLE T1 INNER JOIN (SELECT ID, MAX(Date) DATE FROM YOUR_TABLE GROUP BY ID) T2 WHERE T1.ID = T2.ID AND T1.DATE = T2.DATE;

enter image description here

我用以下代码创建了它:

UISegmentedControl

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

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! } } ONE时,它会将背景颜色更改为此值(用户手指触摸的时间):

enter image description here

我遗漏了一些代码,用于更改TWO中所选(临时按下)选项的样式。

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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

let normalAttributes: NSDictionary = [
    NSForegroundColorAttributeName: UIColor.gray,
    NSFontAttributeName: fontForSegmentedControl!
]

mySegmentedControl.setTitleTextAttributes(selectedAttributes as [NSObject : AnyObject], for: UIControlState.selected)

以上代码仅为选择添加灰色,因此请将其更改为

let normalAttributes: NSDictionary = [
    NSForegroundColorAttributeName: UIColor.white,
    NSFontAttributeName: fontForSegmentedControl!
]

mySegmentedControl.setTitleTextAttributes(selectedAttributes as [NSObject : AnyObject], for: UIControlState.selected)