Custom UISegmentedControl

后端 未结 10 2101
我寻月下人不归
我寻月下人不归 2020-12-04 10:23

How do I make a custom UISegmentedControl?

I have 2 images, 1 that should be displayed when the segment is active and the other if the segment is inacti

10条回答
  •  孤街浪徒
    2020-12-04 11:06

    Swift 4

    This is how I managed it. Make a segmented control and insert segments using the images. Be sure to set one image as selected as this will be the initial selected index. Also set the backgroundColor and tintColor to clear so that segmented control will only show your image.

    var newSegmentedControl: UISegmentedControl = {
            let segmentedControl = UISegmentedControl()
    
            segmentedControl.insertSegment(with: UIImage(named: "x_Selected.jpg"), at: 0, animated: true)
            segmentedControl.insertSegment(with: UIImage(named: "y_Normal.jpg"), at: 1, animated: true)
    
            segmentedControl.addTarget(self, action: #selector(segmentedControlChanged), for: .valueChanged)
    
            segmentedControl.selectedSegmentIndex = 0
            segmentedControl.backgroundColor = .clear
            segmentedControl.tintColor = .clear            
    
        }()
    

    Function called when the value of segmented control changes.

    @objc func segmentedControlChanged(sender: UISegmentedControl) {
    
        if sender.selectedSegmentIndex == 0 {
            sender.setImage(UIImage(named: "x_Selected.jpg"), forSegmentAt: sender.selectedSegmentIndex)
            sender.setImage(UIImage(named: "y_Normal.jpg"), forSegmentAt: 1)
        } else if sender.selectedSegmentIndex == 1 {
            sender.setImage(UIImage(named: "x_Normal.jpg"), forSegmentAt: 0)
            sender.setImage(UIImage(named: "y_Selected.jpg"), forSegmentAt: sender.selectedSegmentIndex)
        } 
    
    }
    

    Hope you find this useful :)

提交回复
热议问题