0

There are a dozen answers to how to set the font of a UISegmentedControl, but I want to determine what font is being used, without having been manually set.

override func viewDidLoad() {
    super.viewDidLoad()
    let s = segmentedControl.state // normal
    let ta1 = segmentedControl.titleTextAttributes(for: .normal) // nil
    let ta2 = UISegmentedControl.appearance().titleTextAttributes(for: .normal) // nil
}

Apple's API documentation is of no insight.

The ultimate purpose is to use the font to calculate the size of the string, and compare to the segment size (if I can get that) and determine if the title is being truncated. Similar to How do I check if UILabel is truncated?

bshirley
  • 8,217
  • 1
  • 37
  • 43

1 Answers1

0

You can get the font from one of the UILabel instances used to create the UISegmentedControl doing the following:

override func viewDidLoad() {
...
  let font = segmentedControl.subviews(ofType: UILabel.self).first?.font
...
}

Here's the definition of subviews

extension UIView {
  
  func subviews<T>(ofType type: T.Type) -> [T] {
    var views: [T] = self.subviews.compactMap { $0 as? T }
    for view in self.subviews {
      views.append(contentsOf: view.subviews(ofType: type))
    }
    return views
  }
}

Anwuna
  • 1,077
  • 11
  • 18