自定義 UISegmentedControl 樣式

系統的 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 擴展方法,這里大家直接拷貝就能夠使用了,祝大家自定義愉快吧~

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,817評論 25 708
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,837評論 18 139
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,180評論 4 61
  • 又是周六,去領老院看奶奶的日子,起晚了,趕緊收拾出門,不讓小伙伴等我,有一刻想到今天是不是算了,不去了,但是想想不...
    ZN張小楠閱讀 144評論 0 3
  • S將車停在我家后便再沒出現過。那晚大家喝得爛醉,迷糊中S載著我們嗑嗑碰碰,除了幾處鼻青臉腫,倒也安全回家。本打算就...
    江下蟲閱讀 562評論 0 0