Search code examples
swiftuisegmentedcontrol

Segment Control Font size not changing in swift


I have a segmented control and I'm trying to change the font size of the segment titles. I have tried multiple code but it isn't working. This is how I'm changing font size of segmented control:

let font = UIFont.systemFont(ofSize: 16)
segmentControl.setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal)

But when I run the app it isn't changing the font size. This is my all code in viewDidLoad:

let font = UIFont.systemFont(ofSize: 16)
segmentControl.setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal)
let titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.red]
segmentControl.setTitleTextAttributes(titleTextAttributes, for: .selected)
segmentControl.fallBackToPreIOS13Layout(using: UIColor.clear)
segmentControl.font(name: "Helvetica", size: 16)
let titleTextAttributesForSelected = [NSAttributedString.Key.foregroundColor: UIColor.white]
let titleTextAttributesForNormal = [NSAttributedString.Key.foregroundColor: UIColor.gray]
segmentControl.setTitleTextAttributes(titleTextAttributesForSelected, for: .selected)
segmentControl.setTitleTextAttributes(titleTextAttributesForNormal, for: .normal)

Solution

  • try this:

        let font = UIFont.systemFont(ofSize: 16)
    
        let normalAttribute: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: UIColor.gray]
        segmentControl.setTitleTextAttributes(normalAttribute, for: .normal)
    
        let selectedAttribute: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: UIColor.red]
        segmentControl.setTitleTextAttributes(selectedAttribute, for: .selected)