扩展方法段控制代码。
这是最新的 Swift 3.0 [2017 年 3 月]
的工作代码
Extension 方法被创建,作为本机段控件的扩展。
extension UISegmentedControl {
func setSegmentStyle() {
let segmentGrayColor = UIColor(red: 0.889415, green: 0.889436, blue:0.889424, alpha: 1.0 )
setBackgroundImage(imageWithColor(color: backgroundColor!), for: .normal, barMetrics: .default)
setBackgroundImage(imageWithColor(color: tintColor!), for: .selected, barMetrics: .default)
setDividerImage(imageWithColor(color: segmentGrayColor), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
let segAttributes: NSDictionary = [
NSForegroundColorAttributeName: UIColor.gray,
NSFontAttributeName: UIFont(name: "Merriweather-Regular", size: 14)!
]
setTitleTextAttributes(segAttributes as [NSObject : AnyObject], for: UIControlState.normal)
let segAttributesExtra: NSDictionary = [
NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: UIFont(name: "Merriweather-Regular", size: 14)!
]
setTitleTextAttributes(segAttributesExtra as [NSObject : AnyObject], for: UIControlState.selected)
selectedSegmentIndex = -1
self.layer.borderWidth = 1.0
self.layer.cornerRadius = 5.0
self.layer.borderColor = segmentGrayColor.cgColor
self.layer.masksToBounds = true
}
// 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!
}
}
此扩展可用于任何使用 UIsegment 控件的代码中。
myUISegment.setSegmentStyle()
这将应用应用于段控件的所有样式。
注意:在这个示例中,我删除了默认边框,更改了字体,在正常、选定模式下设置了不同的颜色,边框显式地制作了一些颜色。
根据您的要求和颜色,您可以相应地更改为绿色或任何自定义颜色,也显示在示例“segmentGrayColor”中