Skip to content

Instantly share code, notes, and snippets.

@pigigaldi
Created July 15, 2016 16:49
Show Gist options
  • Save pigigaldi/b43107aded8b7437ffcb4ecc0b7edba6 to your computer and use it in GitHub Desktop.
Save pigigaldi/b43107aded8b7437ffcb4ecc0b7edba6 to your computer and use it in GitHub Desktop.
Swift: UISegmentedControl with multiline labels (tested on iOS 9.3).
// Remember to initialize UISegmentedControl with appropriate titles.
extension UISegmentedControl {
func makeMultiline(withFontName fontName: String, fontSize: CGFloat, textColor: UIColor){
for index in 0...self.numberOfSegments - 1 {
let label = UILabel(frame: CGRectMake(0,0,self.frame.width/CGFloat(self.numberOfSegments),self.frame.height))
label.font = UIFont(name: fontName, size: fontSize)
label.textColor = textColor
label.text = self.titleForSegmentAtIndex(index)
label.numberOfLines = 0
label.textAlignment = .Center
label.adjustsFontSizeToFitWidth = true
self.setTitle("", forSegmentAtIndex: index)
self.subviews[index].addSubview(label)
}
}
}
@Fouda
Copy link

Fouda commented Apr 3, 2018

in case you need to change the title color
you need to add in the function "makeMultiline" => label.tag = i

then add this function in the extension

`func setSelectedTitleColor() {

for i in 0...self.numberOfSegments - 1 {

  let label = self.subviews[self.numberOfSegments - 1 - i].subviews[1] as? UILabel

  label?.textColor = label?.tag == self.selectedSegmentIndex ? UIColor.red : UIColor.blue
}

}`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment