ios 故事板中带有自定义字体的属性字符串无法正确加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25925914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:36:18  来源:igfitidea点击:

Attributed string with custom fonts in storyboard does not load correctly

iosswiftios8xcode6nsattributedstring

提问by Allen Hsu

We are using custom fonts in our project. It works well in Xcode 5. In Xcode 6, it works in plain text, attributed string in code. But those attributed strings set in storyboard all revert to Helvetica when running on simulator or device, although they look all right in storyboard.

我们在项目中使用自定义字体。它在 Xcode 5 中运行良好。在 Xcode 6 中,它以纯文本、代码中的属性字符串运行。但是那些在storyboard中设置的属性字符串在模拟器或设备上运行时都会恢复为Helvetica,尽管它们在storyboard中看起来没问题。

I'm not sure if it's a bug of Xcode 6 or iOS 8 SDK, or the way to use custom fonts is changed in Xcode 6 / iOS 8?

我不确定这是 Xcode 6 或 iOS 8 SDK 的错误,还是 Xcode 6 / iOS 8 中使用自定义字体的方式发生了变化?

采纳答案by Antoine

The fix for me was to use an IBDesignableclass:

我的解决方法是使用一个IBDesignable类:

import UIKit

@IBDesignable class TIFAttributedLabel: UILabel {

    @IBInspectable var fontSize: CGFloat = 13.0

    @IBInspectable var fontFamily: String = "DIN Light"

    override func awakeFromNib() {
        var attrString = NSMutableAttributedString(attributedString: self.attributedText)
        attrString.addAttribute(NSFontAttributeName, value: UIFont(name: self.fontFamily, size: self.fontSize)!, range: NSMakeRange(0, attrString.length))
        self.attributedText = attrString
    }
}

Giving you this in the Interface Builder:

在界面生成器中为您提供:

Interface Builder custom font with attributed string

带有属性字符串的 Interface Builder 自定义字体

You can set up your attributedstring just as you normal do, but you'll have to set your fontsize and fontfamily once again in the new available properties.

您可以像往常一样设置您的属性字符串,但您必须在新的可用属性中再次设置您的字体大小和字体系列。

As the Interface Builder is working with the custom font by default, this results in a what you see is what you get, which I prefer when building apps.

由于 Interface Builder 默认使用自定义字体,这会导致所见即所得,这是我在构建应用程序时更喜欢的。

Note

笔记

The reason I'm using this instead of just the plain version is that I'm setting properties on the attributed label like the linespacing, which are not available when using the plain style.

我使用它而不是简单版本的原因是我在属性标签上设置属性,如行间距,在使用普通样式时不可用。

回答by Alan Scarpa

The simplest answer that worked for is to drag the fonts into FontBook. If the fonts are in your project but not in your computer's FontBook, IB sometimes has trouble finding it. Weird, but has worked for me on several occasions.

最简单的答案是将字体拖到 FontBook 中。如果字体在您的项目中但不在您计算机的 FontBook 中,IB 有时很难找到它。很奇怪,但曾多次为我工作。

回答by mahbaleshwar hegde

You can add custom fonts to font book.

您可以将自定义字体添加到字体簿。

Step1: Click on manage fonts. It opens the font book.

第一步:点击管理字体。它打开字体书。

enter image description here

在此处输入图片说明

Step2: Click on plus and add your fonts.

步骤2:点击加号并添加您的字体。

enter image description here

在此处输入图片说明

Next time when you click on font with attributed text newly added font also will show in the list. But make sure your custom font added in info.plist and bundle resources.

下次单击带有属性文本的字体时,新添加的字体也会显示在列表中。但请确保在 info.plist 和捆绑资源中添加了您的自定义字体。

回答by rexsheng

Thanks to this thread, I've come to this solution:

感谢这个线程,我来到了这个解决方案:

private let fontMapping = [
    "HelveticaNeue-Medium": "ITCAvantGardePro-Md",
    "HelveticaNeue": "ITCAvantGardePro-Bk",
    "HelveticaNeue-Bold": "ITCAvantGardePro-Demi",
]

func switchFontFamily(string: NSAttributedString) -> NSAttributedString {
    var result = NSMutableAttributedString(attributedString: string)
    string.enumerateAttribute(NSFontAttributeName, inRange: NSRange(location: 0, length: string.length), options: nil) { (font, range, _) in
        if let font = font as? UIFont {
            result.removeAttribute(NSFontAttributeName, range: range)
            result.addAttribute(NSFontAttributeName, value: UIFont(name: fontMapping[font.fontName]!, size: font.pointSize)!, range: range)
        }
    }
    return result
}

回答by KidA

My solution is a bit of a work around. The real solution is for apple to fix Interface Builder.

我的解决方案有点变通。真正的解决方案是苹果修复Interface Builder。

With it you can mark all the bold and italic text in interface builder using a system font, then at runtime render your custom font. May not be optimal in all cases.

有了它,您可以使用系统字体在界面构建器中标记所有粗体和斜体文本,然后在运行时呈现您的自定义字体。可能并非在所有情况下都是最佳的。

 NSMutableAttributedString* ApplyCustomFont(NSAttributedString *attributedText,
                     UIFont* boldFont,
                     UIFont* italicFont,
                     UIFont* boldItalicFont,
                     UIFont* regularFont)
{

    NSMutableAttributedString *attrib = [[NSMutableAttributedString alloc] initWithAttributedString:attributedText];
    [attrib beginEditing];
    [attrib enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, attrib.length) options:0
                    usingBlock:^(id value, NSRange range, BOOL *stop)
    {
        if (value)
        {
            UIFont *oldFont = (UIFont *)value;
            NSLog(@"%@",oldFont.fontName);

            [attrib removeAttribute:NSFontAttributeName range:range];

            if([oldFont.fontName rangeOfString:@"BoldItalic"].location != NSNotFound && boldItalicFont != nil)
                [attrib addAttribute:NSFontAttributeName value:boldItalicFont range:range];
            else if([oldFont.fontName rangeOfString:@"Italic"].location != NSNotFound && italicFont != nil)
                [attrib addAttribute:NSFontAttributeName value:italicFont range:range];
            else if([oldFont.fontName rangeOfString:@"Bold"].location != NSNotFound && boldFont != nil)
                [attrib addAttribute:NSFontAttributeName value:boldFont range:range];
            else if(regularFont != nil)
                [attrib addAttribute:NSFontAttributeName value:regularFont range:range];
        }
    }];
    [attrib endEditing];

    return attrib;
}

Inspired by this post

受到这篇文章的启发

回答by ghr

I have struggled with this bug: UILabel displays correctly in IB with custom font but does not display correctly on device or simulator (font is included in the project and is used in plain UILabels).

我一直在努力解决这个错误:UILabel 在 IB 中使用自定义字体正确显示,但在设备或模拟器上无法正确显示(字体包含在项目中并用于普通 UILabels)。

Finally found Attributed String Creator on (Mac) App Store. Generates code to be placed in your app in the appropriate place. Fantastic. I am not the creator, just a happy user.

终于在 (Mac) App Store 上找到了 Attributed String Creator。生成要放置在您的应用程序中适当位置的代码。极好的。我不是创造者,只是一个快乐的用户。

回答by Zhihao Yang

Met the same problem: the attribute font set for TextView in storyboard didn't work in run time with XCode 6.1 & iOS 8 SDK.

遇到了同样的问题:在使用 XCode 6.1 和 iOS 8 SDK 时,故事板中为 TextView 设置的属性字体在运行时不起作用。

This is how I solved this issue, might be a workaround for you:

这就是我解决此问题的方法,可能是您的解决方法:

  1. open the attribute inspector of your textview, change text to "Plain"

  2. click on the cross to delete the "wC hR"(red below)

    enter image description here

  3. change text to "Attributed", and then you can set the font and size for your text.

  4. run to check if it works
  1. 打开文本视图的属性检查器,将文本更改为“Plain”

  2. 点击十字删除“wC hR”(下图红色)

    在此处输入图片说明

  3. 将文本更改为“属性化”,然后您可以设置文本的字体和大小。

  4. 运行以检查它是否有效

回答by Praveen Sevta

Met the same problem: the attribute font for UILabel in storyboard didn't work in run time. Using this UIFont+IBCustomFonts.m works for me https://github.com/deni2s/IBCustomFonts

遇到同样的问题:storyboard 中 UILabel 的属性字体在运行时不起作用。使用这个 UIFont+IBCustomFonts.m 对我有用 https://github.com/deni2s/IBCustomFonts

回答by Silversky Technology

Try this it will work

试试这个它会工作

In my case when i try to set "Silversky Technology" as Attributed text for label from interface builder its not show when i run in simulator but its show in interface builder. So i used one trick i made Silversky font with 1 pixel bigger then Technology text.

在我的情况下,当我尝试将“Silversky Technology”设置为来自界面构建器的标签的属性文本时,它在模拟器中运行时不显示,但在界面构建器中显示。所以我使用了一种技巧,我使 Silversky 字体比技术文本大 1 个像素。

Attribute text have issue with same size of font so change size of 1 word thisthing work with me.

属性文本具有相同大小的字体问题,因此更改 1 个单词的大小这件事对我有用。

May be this is xcode bug but this trick work for me.

可能这是 xcode 错误,但这个技巧对我有用。

回答by Maselko

The same problem.

同样的问题。

Solved: Just check Selectable in TextView. Without this i have standard System font.

已解决:只需在 TextView 中选中 Selectable。没有这个,我有标准的系统字体。