且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自定义字体仅在Interface Builder中设置时可用

更新时间:2023-02-26 21:43:50


当我尝试以编程方式使用它时,它不起作用,当我打印出可用字体列表时它不显示


这证明您实际上已将正确地包含在目标和 Info.plist 中。



似乎在IB中工作的原因是该字体在您的计算机上也存在 。但事实上,如果你在你的设备上运行这个应用程序,你会发现即使在IB中设置字体也不起作用。



你的字体是特殊精英。正如您所看到的,我在运行的应用程序中可以看到它:





以下是我使用的代码:

 让lab = UILabel()
lab.text =这是一个测试
lab.font = UIFont(名称:SpecialElite-Regular,大小:18)
lab.sizeToFit()
lab.frame.origin = CGPointMake(100,100)
self.view.addSubview(lab)

所以你看, 可以在代码中引用这个字体 - 如果正确加载。您显然没有正确加载它。它不在您的应用程序包中,或者它不在复制构建阶段,或者它未正确列在 Info.plist 中。



(当然,总是有可能你用 [UIFont fontWithName:size:] 调用名称或大小的错误值。)


I have added a custom font to my project. It is included in the target, and it is added in the plist. When I try to use it programmatically it doesn't work, and it doesn't show up when I print out a list of available fonts. However, it does show up as an option in Interface Builder, and if I set a label's text to that font in IB, it works correctly and shows up when I print out a list of available fonts. This is XCode 6.4 and iOS 8.0

When it is working via IB, it gets printed out in the font names like this: Special Elite SpecialElite-Regular

I call the font programmatically like: [UIFont fontWithName:@"SpecialElite-Regular" size:fontSize];

There are no problems when doing this with the built-in fonts.

When I try to use it programmatically it doesn't work, and it doesn't show up when I print out a list of available fonts

This proves that you have not in fact included it properly in the target and the Info.plist.

The reason it seems to work in IB is that this font is also present on your computer. But in fact if you were to run this app on your device, you would see that even setting the font in IB is not working.

Your font is Special Elite. As you can see, I have it visible here in my running app:

Here's the code that I used:

    let lab = UILabel()
    lab.text = "This is a test"
    lab.font = UIFont(name:"SpecialElite-Regular", size:18)
    lab.sizeToFit()
    lab.frame.origin = CGPointMake(100,100)
    self.view.addSubview(lab)

So you see, it is possible to refer to this font in code — if it is loaded properly. You are evidently not loading it properly. It's not in your app bundle, or it's not in the copy build phase, or it's not correctly listed in your Info.plist.

(Of course there's always a possibility that you're calling [UIFont fontWithName:size:] with a bad value for the name or for the size.)