Search code examples
swiftfontsuilabeluisegmentedcontrol

Adjust font size in UisegmentControl


how can I adjustfontsize in segmentcontrol like a label that it has a property named adjustsFontSizeToFitWidth so if the text is larger that label width the font size will become smaller to fit the width how can I. do same for uisegmetncontrol?


Solution

  • Use setTitleTextAttrribute to set font for for segment control

      SegmentControl.setTitleTextAttributes([NSFontAttributeName: UIFont(name: REGULAR_FONT, size: 13.0)],
                                                               for: UIControlState())
       SegmentControl.setTitleTextAttributes([NSFontAttributeName: UIFont(name: BOLD_FONT, size: 13.0)], for:.selected)
    

    Added the swift version of answer mentioned in the comment:-

     func setWidthTosegmetControl(view :UIView)  {
            let subviews = view.subviews
            for subview in subviews {
                if subview is UILabel {
                    let label: UILabel? = (subview as? UILabel)
                    print("label found: \(label?.text)")
                    label?.adjustsFontSizeToFitWidth = true
                    label?.minimumScaleFactor = 0.1
                }else {
                    setWidthTosegmetControl(view: subview)
                }
            }
        }
    

    enter image description here