ios - 自定义字体错误

标签 ios swift xcode9

TL;DR:在 Storyboard/xib 中使用自定义字体之前,不能以编程方式使用它们。

注意:我已经查看了 this ,尝试了答案,但没有用。我还确保他们是目标成员。

我在将段控件标题更改为自定义字体时注意到一个奇怪的错误:

segmentedControl.titleTextAttributes = NSDictionary(objects: [UIFont.init(name: "Comfortaa-Regular",
                                                                          size: UIFont.systemFontSize)!,
                                                              UIColor.white],
                                                    forKeys: [NSAttributedStringKey.font as NSCopying,
                                                              NSAttributedStringKey.foregroundColor as NSCopying]) as? [AnyHashable : Any]

找不到字体,所以解包失败。但是在 Storyboard 中可以看到字体。

FontList

它已正确添加到项目中,这是 CopyBundle 和 InfoList:

CopyBundleResources

InfoPlist

所以这里有问题;如果我在 Storyboard 中使用它,它会显示在字体系列中:

ComfortaaBold

但如果不是,则不会显示-此处我已更改为浅色且粗体已消失-,并且不能以编程方式使用。

ComfortaaLight

我使用的是 Xcode 版本 9.0 (9A235) 和 Swift 4。我还检查了 OpenRadar,但找不到与此相关的提交。

提到的字体:Comfortaa

最佳答案

@EDUsta,我只是尝试使用给定的字体,它的工作正常,没有问题,给出了我遵循的步骤:

  1. 添加 Comfortaa-Bold.ttf , Comfortaa-Light.ttf , Comfortaa-Regular.ttf要投影的字体文件。

enter image description here

2.在info.plist中添加Fonts条目文件

enter image description here

确保项目目标中添加的字体。

之后,在 UILabel 上应用字体和 UISegmentedControl使用 Swift代码如下:

   let fontFirst = UIFont(name: "Comfortaa-Bold", size: 16.0)!
    segmentFont.setTitleTextAttributes([NSAttributedStringKey.font : fontFirst, NSAttributedStringKey.foregroundColor : UIColor.red],
                                       for: .normal)

    labelBold.font = UIFont(name: "Comfortaa-Bold", size: 16.0)
    labelLight.font = UIFont(name: "Comfortaa-Light", size: 16.0)
    labelRegular.font = UIFont(name: "Comfortaa-Regular", size: 16.0)

它的工作非常完美,您可以在下面的屏幕截图中查看:

enter image description here

为了您的引用,我添加了完整的项目 here:

关于ios - 自定义字体错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46604829/

相关文章:

ios - 使用 Swift 在 SpriteKit 中将自定义 "number"图像添加到 SKLabelNode 作为分数

iphone - 子类 UIViewController 以编程方式创建列表而不使用 nib

swift - NSCollectionViewItem 的圆角

swift - 如何在运行时修改view.alphaValue并生效

ios - 如何创建具有复杂内容的 UITableViewCells 以保持滚动流畅

swift - `Calendar` API 崩溃 Swift Playground

仅IOS 11 : Navigation bar label off on top

ios - textFieldShouldReturn 和 shouldChangeCharactersInRange

swift - 简单 IsEqualTo 密码,需要建议

html - iOS WKWebView HTML5 音频在手机锁定后约 30 秒后停止