swift 自定义分段控制

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 自定义分段控制相关的知识,希望对你有一定的参考价值。


import UIKit

@IBDesignable class CustomSegmentedControl: UISegmentedControl {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }

    func update(){
        let attributes = [ NSAttributedString.Key.foregroundColor: UIColor.white ]
        setTitleTextAttributes(attributes, for: .normal)
        setTitleTextAttributes(attributes, for: .selected)
        for index in 0 ..< numberOfSegments {
            if let image = imageForSegment(at: index)?.withRenderingMode(.alwaysOriginal) {
                setImage(image, forSegmentAt: index)
            }
        }
    }

     func setupView() {
        let insets = UIEdgeInsets(top: 7, left: 7, bottom: 7, right: 7)
        let backgroundNormal = #imageLiteral(resourceName: "SegmentedControl-Background-Normal").resizableImage(withCapInsets: insets, resizingMode: .stretch)
        let backgroundSelected = #imageLiteral(resourceName: "SegmentedControl-Background-Selected").resizableImage(withCapInsets: insets, resizingMode: .stretch)
        let attributes = [ NSAttributedString.Key.foregroundColor: UIColor.white ]

        setBackgroundImage(backgroundNormal, for: .normal, barMetrics: .default)
        setBackgroundImage(backgroundSelected, for: .selected, barMetrics: .default)
        setDividerImage(#imageLiteral(resourceName: "SegmentedControl-Divider-NormalNormal"), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
        setDividerImage(#imageLiteral(resourceName: "SegmentedControl-Divider-SelectedNormal"), forLeftSegmentState: .selected, rightSegmentState: .normal, barMetrics: .default)
        setDividerImage(#imageLiteral(resourceName: "SegmentedControl-Divider-NormalSelected"), forLeftSegmentState: .normal, rightSegmentState: .selected, barMetrics: .default)

        setTitleTextAttributes(attributes, for: .normal)
        setTitleTextAttributes(attributes, for: .selected)
        for index in 0 ..< numberOfSegments {
            if let image = imageForSegment(at: index)?.withRenderingMode(.alwaysOriginal) {
                setImage(image, forSegmentAt: index)
            }
        }
    }
}

以上是关于swift 自定义分段控制的主要内容,如果未能解决你的问题,请参考以下文章

Swift 自定义分段控件 SegmentedControl

在 Swift 的标头中使用分段控件更改 UICollectionView 的内容

Swift - 分段控制 - 切换多个视图

Swift 分段控制和 UITableView

Swift - 如何让分段控制锁定在屏幕顶部

Swift 在尝试访问分段控制索引时抛出错误