简体   繁体   English

如何确定 UISegmentedControl 中使用的字体(默认情况下)?

[英]How do I determine what font is being used (by default) in the UISegmentedControl?

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.关于如何设置UISegmentedControl的字体有十几个答案,但我想确定正在使用的字体,而无需手动设置。

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. Apple 的 API 文档没有洞察力。

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?类似于如何检查 UILabel 是否被截断?

You can get the font from one of the UILabel instances used to create the UISegmentedControl doing the following:您可以从用于创建UISegmentedControlUILabel实例之一获取字体,执行以下操作:

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

Here's the definition of subviews这是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
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不更改字体大小的情况下更改swift中UISegmentedControl的字体? - How do I change the font of a UISegmentedControl in swift without changing the font size? 如何更改 UISegmentedControl 索引更改时显示的内容? - How do I change what is shown when the UISegmentedControl index is changed? 自定义字体中的“上下文替代项”被用作默认值 - “Contextual Alternates” in a custom font is being used as default 我目前正在检查UIAlertController是否存在,以确定正在使用的操作系统版本。 有没有更有效的方法可以做到这一点? - I'm currently checking if UIAlertController exists to determine what OS version is being used. Is there a more efficient way to do this? 如何使用UISegmentedControl切换视图? - How do I use a UISegmentedControl to switch views? 如何将UISegmentedControl绑定到ViewModel命令? - How do I bind a UISegmentedControl to a ViewModel command? iOS:当我尝试使用西方字体显示日语字符时,如何找出使用的“后备字体”? - iOS: How do I find out what “fallback font” is used when I try to display Japanese characters with my western font? 如何在UISegmentedControl中为所选元素设置字体? - How can I set the font for the selected element in a UISegmentedControl? 如何以编程方式显示UISegmentedControl? - How do I programmatically display a UISegmentedControl? 如何以编程方式向UISegmentedControl添加约束 - How do I add constraints programmatically to UISegmentedControl
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM