在UisegmentControl中调整字体大小

时间:2017-04-12 07:32:51

标签: swift fonts uilabel uisegmentedcontrol

如何在segmentcontrol中调整字体大小,就像它有一个名为adjustsFontSizeToFitWidth的属性的标签一样,如果文本大于标签宽度,字体大小将变小以适应宽度我怎么能为uisegmetncontrol做同样的事情?

2 个答案:

答案 0 :(得分:2)

使用setTitleTextAttrribute设置段控制的字体

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

添加了评论中提到的答案的快速版本: -

 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

答案 1 :(得分:0)

我必须在视图控制器中执行此操作并在 viewDidAppear 中调用该函数。

func autoshrinkSegmentFontSize() {
    for subview in segments.subviews {
        for label in subview.subviews {
            if let myLabel = subview as? UILabel {
                myLabel.adjustsFontSizeToFitWidth = true
                myLabel.minimumScaleFactor = 0.5
            }
        }
    }
}