系統的 UISegmentedControl 是個挺方便的控件,這里來講講在 Swift3 下自定義 UISegmentedControl 的樣式,包括修改底色,邊框顏色等等。
要了解 UISegmentedControl 各個部分的組成,可以在官方的文檔中找到 UISegmentedControl 文檔 。著重注意這個圖:
image.png
上面這幅圖明確的列出了 UISegmentedControl 各個部分所控制的方法。下面就開始自定義吧。
首先我們先做一個通過顏色生成圖片的的一個擴展方法:
extension UIImage{
public class func renderImageWithColor(_ color: UIColor, size: CGSize) -> UIImage {
UIGraphicsBeginImageContext(size)
guard let context = UIGraphicsGetCurrentContext() else {
UIGraphicsEndImageContext()
return UIImage()
}
context.setFillColor(color.cgColor);
context.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height));
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img ?? UIImage()
}
}
接著,我們可以為 UISegmentedControl 建立一個可以自定義顏色的擴展方法:
extension UISegmentedControl {
/// 自定義樣式
///
/// - Parameters:
/// - normalColor: 普通狀態下背景色
/// - selectedColor: 選中狀態下背景色
/// - dividerColor: 選項之間的分割線顏色
func setSegmentStyle(normalColor: UIColor, selectedColor: UIColor, dividerColor: UIColor) {
let normalColorImage = UIImage.renderImageWithColor(normalColor, size: CGSize(width: 1.0, height: 1.0))
let selectedColorImage = UIImage.renderImageWithColor(selectedColor, size: CGSize(width: 1.0, height: 1.0))
let dividerColorImage = UIImage.renderImageWithColor(dividerColor, size: CGSize(width: 1.0, height: 1.0))
setBackgroundImage(normalColorImage, for: .normal, barMetrics: .default)
setBackgroundImage(selectedColorImage, for: .selected, barMetrics: .default)
setDividerImage(dividerColorImage, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
let segAttributesNormal: NSDictionary = [NSForegroundColorAttributeName: UIColor.gray, NSFontAttributeName: UIFont.systemFont(ofSize: 14)]
let segAttributesSeleted: NSDictionary = [NSForegroundColorAttributeName: UIColor.white,NSFontAttributeName: UIFont.systemFont(ofSize: 14)]
// 文字在兩種狀態下的顏色
setTitleTextAttributes(segAttributesNormal as [NSObject : AnyObject], for: UIControlState.normal)
setTitleTextAttributes(segAttributesSeleted as [NSObject : AnyObject], for: UIControlState.selected)
// 邊界顏色、圓角
self.layer.borderWidth = 0.7
self.layer.cornerRadius = 5.0
self.layer.borderColor = dividerColor.cgColor
self.layer.masksToBounds = true
}
}
這個擴展方法我只暴露了三種顏色的修改,大家可以根據自己需求修改。
最后就是使用了,注意這里如果進行了自定義,不能用 autoLayout 了, 需指定 Segement 的位置大小,不然顯示出來的效果被壓縮成了一條線,我估計是 setBackgroundImage 的方法需要把 1x1 的顏色圖片進行填充,如果不指定大小會出差錯。
let segment = UISegmentedControl(items: ["測試", "測試", "測試"])
segment.frame = CGRect(x: 0, y: 0, width: 150, height: 40)
segment.setSegmentStyle(normalColor: UIColor.clear, selectedColor: UIColor.cyan, dividerColor: UIColor.gray)
segment.selectedSegmentIndex = 0
view.addSubview(segment)
image.png
個人比較喜歡用 extension 擴展方法,這里大家直接拷貝就能夠使用了,祝大家自定義愉快吧~