class exampleUISegmentedControl : UISegmentedControl {

    

    let bottomBar = UIView()

    

    override init(frame: CGRect) {

        super.init(frame: frame)

        self.backgroundColor = .clear

        self.tintColor = .clear

        self.insertSegment(withTitle: "page1", at: 0, animated: true)

        self.insertSegment(withTitle: "page2", at: 1, animated: true)

        self.selectedSegmentIndex = 0

        self.translatesAutoresizingMaskIntoConstraints = false

        

        self.setTitleTextAttributes([

            NSAttributedStringKey.font : UIFont.init(name: "NanumSquareOTFEB", size: 14)!,

            NSAttributedStringKey.foregroundColor : UIColor(red: 128, green: 128, blue: 128)

            ], for: .normal)

        self.setTitleTextAttributes([

            NSAttributedStringKey.font : UIFont.init(name: "NanumSquareOTFEB", size: 14)!,

            NSAttributedStringKey.foregroundColor : UIColor(red: 62, green: 62, blue: 62)

            ], for: .selected)

        

        bottomBar.translatesAutoresizingMaskIntoConstraints = false

        bottomBar.backgroundColor = UIColor(red: 62, green: 62, blue: 62)

        self.addSubview(bottomBar)

        

        let bottmBarWidth = UIScreen.main.bounds.width / CGFloat(self.numberOfSegments)

        

        bottomBar.snp.makeConstraints { (make) in

            make.top.equalTo(self.snp.bottom)

            make.height.equalTo(3)

            make.width.equalTo(bottmBarWidth)

            make.left.equalTo(self.snp.left)

        }

        

        self.addTarget(self, action: #selector(valueChanged), for: .valueChanged)

    }

    

    @objc func valueChanged() {

        UIView.animate(withDuration: 0.1) {

            self.bottomBar.frame.origin.x = (self.frame.width / CGFloat(self.numberOfSegments)) * CGFloat(self.selectedSegmentIndex)

        }

    }

    

    required init?(coder aDecoder: NSCoder) {

        fatalError("exampleUISegmentedControl")

    }

    

    @objc func segmentedControlValueChanged(_ sender: UISegmentedControl) { //for example

        UIView.animate(withDuration: 0.3) {

            self.bottomBar.frame.origin.x = (self.frame.width / CGFloat(self.numberOfSegments)) * CGFloat(self.selectedSegmentIndex)

        }

    }

}


+ Recent posts