Scroll dynamic UISegmentedControl in Swift 3

Sathya Baman picture Sathya Baman · Oct 2, 2017 · Viewed 7.5k times · Source

Hi i want to create a dynamic UISegmented View with more than 20 Items. I tried it, but the output is like this.

enter image description here

the text is sliced not visible fully. I want it to scroll to the left and right and also display the full text. can some one help me to fix this. tnx

View Controller

override func viewDidLoad() {
    super.viewDidLoad()

    let items = ["All Fruits", "Orange", "Grapes", "Banana",  "Mango", "papaya", "coconut", "django"]
    let filtersSegment = UISegmentedControl(items: items)
    filtersSegment.frame = CGRect.init(x: 10, y: 60, width: 300, height: 50)
    filtersSegment.selectedSegmentIndex = 0
    filtersSegment.tintColor = UIColor.black
    filtersSegment.addTarget(self, action: #selector(self.filterApply), for: UIControlEvents.valueChanged)
    self.view.addSubview(filtersSegment)
}

@objc private func filterApply(segment:UISegmentedControl) -> Void {
    print("Selected Index : \(segment.selectedSegmentIndex)")
}

Answer

Ketan Parmar picture Ketan Parmar · Oct 2, 2017

You can try like

[[UILabel appearanceWhenContainedIn:[UISegmentedControl class], nil] setNumberOfLines:0];

segment.apportionsSegmentWidthsByContent = YES;

Swift :

Something like,

   UILabel.appearance(whenContainedInInstancesOf: [UISegmentedControl.self]).numberOfLines = 0
   segment.apportionsSegmentWidthsByContent = true

and you can take your segmented control in scrollview. But with UISegmentedControl you should not use more than four or five segment. It's main purpose is to show three or four options! You should try different mechanism to achieve your goal!

You should refer this post also if it can help!