UISegmentedControl selected state icon image

后端 未结 6 1704
执笔经年
执笔经年 2021-02-20 07:54

How can I set the icon image for selected state of the UISegmentedControl. Is the UISegmentedControl really missing this functionality or

6条回答
  •  爱一瞬间的悲伤
    2021-02-20 08:23

    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 images.

    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.. :)

提交回复
热议问题