ios – 如果用户在Swift中选择了UISegmentedControl,该怎么改?

这是我的UISegmentedControl写在 Swift

我用以下代码创建了它:

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或TWO时,将背景颜色更改为(用户手指触摸的时间):

我在UISegmentedControl中缺少一些用于选择(临时按下)选项的样式的代码.

如何清除深灰色的选择并留下清晰的颜色?

解决方法

类似于您已经设置了UIControlState.normal的背景图像,您需要为UIControlState.highlighted和UIControlState.selected UIControlState.highlighted设置适当的图像.

将以下代码添加到您的扩展功能removeBorders()(假设您想要有一个明确的背景,按下未选择的段和一个色调的背景被按下选定的一个):

setBackgroundImage(imageWithColor(color: .clear),for: .highlighted,barMetrics: .default)
setBackgroundImage(imageWithColor(color: tintColor!),for: [.selected,.highlighted],barMetrics: .default)

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...