Swift – how to change font size and font name of uisegmentedcontrol programmatically on swift

swiftuisegmentedcontrol

How to change font size and font name of uisegmentedcontrol programmatically? I used swift.

Here is my code:

self.mysegmentedControl = UISegmentedControl(items: [
        NSLocalizedString("Aaaaaa", comment: ""),
        NSLocalizedString("Bbbbbb", comment: ""),
        NSLocalizedString("Cccccc", comment: ""),
        NSLocalizedString("Dddddd", comment: ""),
        NSLocalizedString("Eeeeee", comment: ""),
        ])
self.mysegmentedControl.addTarget(self, action: "mysegmentedControlDidChange:", forControlEvents: .ValueChanged)
self.mysegmentedControl.selectedSegmentIndex = 0

regards.

Best Answer

UI can use control appearance, best place to add it is in app delegate, didFinishLaunchingWithOptions method, use this if you want to set up the same attribute to every UISegmentedControls in your project just once:

let attr = NSDictionary(object: UIFont(name: "HelveticaNeue-Bold", size: 16.0)!, forKey: NSFontAttributeName)
UISegmentedControl.appearance().setTitleTextAttributes(attr as [NSObject : AnyObject] , forState: .Normal)

But if you are going to set up attributes to just one UISegmentedControl or if you want to change it more often base on some condition use this, UISegmentedControl method:

func setTitleTextAttributes(_ attributes: [NSObject : AnyObject]?,
                   forState state: UIControlState)

Example:

let attr = NSDictionary(object: UIFont(name: "HelveticaNeue-Bold", size: 16.0)!, forKey: NSFontAttributeName)
seg.setTitleTextAttributes(attr as [NSObject : AnyObject] , forState: .Normal)