I want to adjust the width size with iOS segment control.

Asked 1 years ago, Updated 1 years ago, 119 views

I have a question about UISegmentControl.
In SegmentControl like the attached image,
without changing the overall size when selecting "First" Is it possible to increase the width of "Fisrt" and reduce the width of "second"?

That's all.I look forward to your kind cooperation.

Enter a description of the image here

swift ios objective-c

2022-09-30 21:38

1 Answers

UISegmentedControl public API does not have any particular selection/non-selection to change the width of each segment, so you can write a little code.

import UIKit

classViewController:UIViewController {

    @IBOutlet weak var segmentedControl:UISegmentedControl!

    override func viewDidLoad(){
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let normalAttr: NNSAttributedString.Key:Any = [
            .font —UIFont.systemFont (ofSize:12)
        ]
        segmentedControl.setTitleTextAttributes (normalAttr, for:.normal)
        let selectedAttr: NNSAttributedString.Key:Any = [
            .font —UIFont.boldSystemFont (ofSize:18)
        ]
        segmentedControl.setTitleTextAttributes (selectedAttr, for:.selected)

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

    @objc funcsegmentValueChanged(_sender:UISegmentedControl){
        for in 0..<sender.numberOfSegments{
            let width —CGFloat=sender.selectedSegmentIndex==i?80:60
            sender.setWidth (width, forSegmentAt:i)
        }
        //...
    }

    //...
}

St On the Storyboard, set the total width of the selected segment (one 80 in the above example) and one non-selected segment (one 60 in the above example) (=140).
また Also, the action of UISegmentedControl is assumed to be not connected on the Storyboard.

First selected
Second selected

This example distinguishes between the font in the selected state and the font in the non-selected state, but if you don't need that part, you don't need eight lines from let normalAttr....


2022-09-30 21:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.