xcode 当文本设置为“属性”时,带有自定义字体的 UITextView 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31102398/
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
UITextView with custom font not working when text set to "attributed"
提问by Franck
I have a UITextView
with some text that came from a .rtf (pasted directly onto Xcode)
我有UITextView
一些来自 .rtf 的文本(直接粘贴到 Xcode 上)
The context contain only one custom font (Futura Book BT 11.0)
上下文仅包含一种自定义字体(Futura Book BT 11.0)
If I set the "text(attributed)" property to "plain"= The custom font appear properly from the storyboard and from the app
如果我将“text(attributed)”属性设置为“plain”=自定义字体从故事板和应用程序中正确显示
If I set the "text" property to "attributed"=. The custom font appear properly from the storyboard BUT not from the app.
如果我将“text”属性设置为“attributed”=。自定义字体从情节提要中正确显示,但不能从应用程序中显示。
As my goal was to have a text with multiple font working, how to have the attributed property to work with custom fonts? (Swift)
由于我的目标是使用多种字体的文本,如何让属性与自定义字体一起使用?(迅速)
Thanks!
谢谢!
回答by scott
The custom font appear properly from the storyboard BUT not from the app.
自定义字体从情节提要中正确显示,但不能从应用程序中显示。
Does the app not show the font at all, or does it restore to system font? If it is reverting to Helvetica, it looks like this may be a known bug in iOS 8.1 http://openradar.appspot.com/radar?id=5117089870249984
应用程序根本不显示字体,还是恢复到系统字体?如果它恢复到 Helvetica,看起来这可能是 iOS 8.1 中的一个已知错误 http://openradar.appspot.com/radar?id=5117089870249984
Possible Solution:Did you test it on the simulator and a device? It could be that it just doesn't work on the simulator, which means you could fix it by installing the font on your system.
可能的解决方案:您是否在模拟器和设备上对其进行了测试?可能是它在模拟器上不起作用,这意味着您可以通过在系统上安装字体来修复它。
回答by Bilal Ahmad
I have faced the same problem when I used multiple custom fonts in attributed UILabel. Storyboard shows correct result but device does not!!
当我在属性 UILabel 中使用多个自定义字体时,我遇到了同样的问题。故事板显示正确的结果,但设备没有!!
What I have find out that if the font size is different of text with different custom fonts. It works fine!!
我发现如果字体大小与具有不同自定义字体的文本不同。它工作正常!!
So for now I use font size with minor difference. Like if one is 14 I used 14.01 for the other. Its not possible inside storyboard so I opened storyboard as source code and manually set font size like:
所以现在我使用的字体大小略有不同。就像如果一个是 14,我使用 14.01 作为另一个。在情节提要中不可能,所以我打开情节提要作为源代码并手动设置字体大小,例如:
<attributedString key="attributedTitle">
<fragment content="Do not have account? ">
<attributes>
<color key="NSColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="calibratedRGB"/>
<font key="NSFont" size="14" name="Roboto-Light"/>
<paragraphStyle key="NSParagraphStyle" alignment="center" lineBreakMode="wordWrapping" baseWritingDirection="natural" tighteningFactorForTruncation="0.0"/>
</attributes>
</fragment>
<fragment content="Login">
<attributes>
<color key="NSColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="calibratedRGB"/>
<font key="NSFont" size="14.01" name="Roboto-Bold"/>
<paragraphStyle key="NSParagraphStyle" alignment="center" lineBreakMode="wordWrapping" baseWritingDirection="natural" tighteningFactorForTruncation="0.0"/>
</attributes>
</fragment>
<attributedString key="attributedTitle">
But still I am unable to find why it happens!
但我仍然无法找到它发生的原因!
回答by Orion
What I do:
我所做的:
private var _mutableString: NSMutableAttributedString!
if !isTitle {
var titleFont: UIFont = UIFont(name: StyleGlobals.TitleFontName, size: StyleGlobals.TitleFontSize)!
self._mutableString.addAttribute(NSFontAttributeName, value: titleFont, range: NSMakeRange(0, count(self._mutableString.string)))
self._mutableString.addAttribute(NSForegroundColorAttributeName, value: StyleGlobals.FontColor, range: NSMakeRange(0, count(self._mutableString.string)))
}
self.Label.attributedText = self._mutableString
This applies both a new font color as well as the font itself. I have a certain UILabel that is has to be able to contain different fonts. It can either be a Title or a subtitle. Hence I had to apply the font when I had determined what the Label is going to contain.
这适用于新字体颜色以及字体本身。我有一个特定的 UILabel 必须能够包含不同的字体。它可以是标题或副标题。因此,当我确定 Label 将包含的内容时,我必须应用字体。
回答by freytag
Did you make sure that "Futura Book BT" is correctly added as a custom font in your app?
您是否确保“Futura Book BT”作为自定义字体正确添加到您的应用程序中?
回答by AngelMixu
In my case the problem was that I didn't have the font installed on my system, so I did it with Font Book. Then, the font appeared on the list in attributed text labels.
就我而言,问题是我的系统上没有安装该字体,所以我使用 Font Book 进行了安装。然后,字体出现在属性文本标签的列表中。
EDIT:Now I had some problems for displaying my current text and did this (I'm using a UILabel, not tested on UITextView):
编辑:现在我在显示当前文本时遇到了一些问题并执行了此操作(我使用的是 UILabel,未在 UITextView 上进行测试):
My solution is to create an attributed string from html (saw this extension somewhere here in SO):
我的解决方案是从 html 创建一个属性字符串(在 SO 中的某处看到了这个扩展):
extension String {
var html2AttStr: NSAttributedString? {
guard let data = dataUsingEncoding(NSUTF8StringEncoding) else { return nil }
do {
return try NSAttributedString(data: data,
options: [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding],
documentAttributes: nil)
} catch let error as NSError {
//print(error.code)
return nil
}
}
}
And then what I do is something like:
然后我做的是这样的:
let htmlStyle = "<meta charset=\"UTF-8\"><style> body { font-family: 'SourceSansPro-Light'; font-size: 18px; text-align: center; } b {font-family: 'SourceSansPro-Light'; }</style>"
let myString = "<font size=\"+2\">Slightly bigger font</font><br><br>Some message with normal text <b>a bold text</b> and some more text"
var attributedString = htmlStyle
attributedString.appendContentsOf(myString)
informationLabel.attributedText = attributedString.html2AttStr
One of the advantages of this is that I can now put some '%s' text inside the string for parsing with a word/number/etc. and It's easier to translate and parse. With formatted text I had to make a bunch of code for finding text, applying format without touching anything around. This works pretty well for me :)
这样做的优点之一是我现在可以在字符串中放入一些 '%s' 文本以使用单词/数字/等进行解析。并且更容易翻译和解析。对于格式化文本,我不得不编写一堆代码来查找文本,应用格式而不触及任何东西。这对我来说效果很好:)
回答by Nikola Jovic
Please call all your code in viewDidLayoutSubviewsmethod! Than works. I have many problems when chanhing font size, style i viewDidLoad or viewWillApperar methods.
请在viewDidLayoutSubviews方法中调用所有代码!比工作。我在更改字体大小、样式时遇到很多问题,我 viewDidLoad 或 viewWillApperar 方法。
So just move your code in viewDidLayoutSubviewsmethod. You can use flag to change fonts only once since this method can be called many times :]
所以只需在viewDidLayoutSubviews方法中移动您的代码。您只能使用标志更改字体一次,因为此方法可以多次调用:]
回答by Nilesh R Patel
You can use this extension
你可以使用这个扩展
extension NSMutableAttributedString {
func createAttributedString(word : NSArray, attributeCustomizeFont:UIFont, defaultFont : UIFont, defaultColor : UIColor, allowSpecing : Bool , allowUnderLine : Bool = false) -> NSAttributedString {
self.addAttribute(NSAttributedString.Key.font, value: defaultFont, range: (self.string as NSString).range(of: self.string))
if allowSpecing {
self.addAttribute(NSAttributedString.Key.kern, value: NSNumber(value: 5), range: (self.string as NSString).range(of: self.string))
}else {
self.addAttribute(NSAttributedString.Key.kern, value: NSNumber(value: 0), range: (self.string as NSString).range(of: self.string))
}
self.addAttribute(NSAttributedString.Key.foregroundColor, value: defaultColor, range: (self.string as NSString).range(of: self.string))
for i in 0..<word.count {
self.addAttribute(NSAttributedString.Key.font, value: attributeCustomizeFont, range: (self.string as NSString).range(of: word.object(at: i) as! String))
}
if allowUnderLine {
self.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: (self.string as NSString).range(of: self.string))
}
return self
}
}
How to use extension
如何使用扩展
var attributedString = NSMutableAttributedString(string:"Test for set custom font")
attributedString = attributedString.createAttributedString(word: ["custom font"], attributeCustomizeFont: UIFont(name: "Arial", size: 18)! , defaultFont: UIFont(name: "Helvetica", size: 15)!, defaultColor: UIColor.black, allowSpecing: false) as! NSMutableAttributedString
So the whole string font set 'Helvetica' with size 18 and for 'custom font'text set 'Arial' font with size 15.
因此,整个字符串字体集“Helvetica”大小为 18,“自定义字体”文本集“Arial”字体大小为 15。
回答by SaRaVaNaN DM
Making UITextview "selectable" from storyboard will work.
使 UITextview 从故事板“可选”将起作用。
回答by Fadi
?FIXED :
?固定的 :
Fixed by subclassing my UITextView
as KMPlaceholderTextViewwhich is also useful for adding a placeholder to text view and can be used from Interface Builder as same as UITextField
.
通过将 my 子类UITextView
化为KMPlaceholderTextView进行修复,这对于将占位符添加到文本视图也很有用,并且可以像UITextField
.
Now I can use custom fonts successfully and add placeholder text.
现在我可以成功使用自定义字体并添加占位符文本。
回答by Ishara Meegahawala
There is a workaround. Just double click on font file(in Finder) and install it in to system.
有一个解决方法。只需双击字体文件(在 Finder 中)并将其安装到系统中。