【问题标题】:How can I use a custom font through an entire app in Swift 4 / Xcode 10.1? [duplicate]如何在 Swift 4 / Xcode 10.1 的整个应用程序中使用自定义字体? [复制]
【发布时间】:2019-07-05 17:34:54
【问题描述】:

我在这里尝试了一些答案来为整个应用程序设置自定义字体,但似乎没有一个在 Xcode 10.1 中有效。我想知道是否有人有一些建议?

这是我迄今为止尝试过的;
Using custom font for entire iOS app swift

Set a default font for whole iOS app?

这是一个代码示例:(这仍然是给我系统字体)

override func viewDidLoad() {
    super.viewDidLoad()
    UILabel.appearance().font = UIFont(name: "Times New Roman", size: 17)

    let label1 = UILabel(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
    label1.text = "Hello"
    view.addSubview(label1)
}

谢谢!

【问题讨论】:

  • 您必须将第一个代码添加到 AppDelegate.the swift 文件中的 ``func application(_ application: UIApplication, didFinishLaunchingWithOptions...```
  • 如果您使用的是最新的 swift,请使用此行 UILabel.appearance().font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle(rawValue: "Times New Roman"))
  • 这里有更好的解决方案:stackoverflow.com/questions/8707082/…
  • @brontea cross check font type face name,正确的你需要在这里给出 UIFont(name: "Times New Roman", size: 17)。希望你在plist中添加了字体。跨度>
  • @iOSTeam 是的,我尝试将该行放入 didFinishLaunchingWithOptions 函数中,但仍然没有结果。我会试试你建议的答案

标签: ios swift uilabel


【解决方案1】:

你可以使用 UIFont 的扩展来做

extension UIFont {

   public enum FontWeight {
      //cases are just font family like bold, light, italic
      case .light
   }


   func appFont(weight : FontWeight, size : CGFloat) -> UIFont {
      var fontName = "Times New Roman-"
      switch weight {
         case .light {
             fontName = fontName + "light" // add your family name here
         }
      }
      return UIFont(name: fontName, size: size)!
    }
}

如果是标签

label.font = UIFont.appFont(weight : .light, size : 17)

【讨论】:

  • 有没有办法为所有的 uilabels 设置这个?谢谢
  • @brontea 您可以继承 UILabel 并在其中设置字体,从该子类在您的应用中制作标签。
  • 这是个好主意,谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-10-22
  • 2012-03-10
  • 1970-01-01
  • 2014-10-07
  • 1970-01-01
  • 2011-11-28
  • 2012-08-30
  • 2016-02-28
相关资源
最近更新 更多