【问题标题】:UITextView with custom font not working when text set to "attributed"当文本设置为“属性”时,具有自定义字体的 UITextView 不起作用
【发布时间】:2015-06-28 17:00:09
【问题描述】:

我有一个 UITextView,其中包含一些来自 .rtf 的文本(直接粘贴到 Xcode 上)

上下文仅包含一种自定义字体(Futura Book BT 11.0)

如果我将“text(attributed)”属性设置为“plain”= 自定义字体从情节提要和应用程序中正确显示

如果我将“text”属性设置为“attributed”=。自定义字体从情节提要中正确显示,但不是从应用程序中显示。

由于我的目标是使用多种字体的文本,如何让属性属性与自定义字体一起使用? (斯威夫特)

谢谢!

【问题讨论】:

    标签: xcode swift nsattributedstring custom-font


    【解决方案1】:

    自定义字体在情节提要中正确显示,但在应用程序中显示不正确。

    应用程序根本不显示字体,还是恢复为系统字体?如果它正在恢复到 Helvetica,看起来这可能是 iOS 8.1 中的一个已知错误 http://openradar.appspot.com/radar?id=5117089870249984

    可能的解决方案: 您是否在模拟器和设备上对其进行了测试?可能是它在模拟器上不起作用,这意味着您可以通过在系统上安装字体来修复它。

    【讨论】:

    • 它正在恢复到 Helvetica。
    • 尝试使用 Font Book 在 Mac 上安装它?
    • openradar.appspot.com/radar?id=5117089870249984 = 知道了。看起来正是这个错误!
    • 将字体添加到 Mac 的 Font Book 应用程序并不能解决问题。看起来它可以解决问题。正如其他答案所示,解决方案是在运行时添加属性字符串。像冠军一样工作。更好的是,将您在 IB 中的字体设置为应该像 Helvetica 一样工作的字体。然后执行此操作:[attrib enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, attrib.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) 并删除字体并添加您的自定义字体。一定要检查粗体、斜体等类型。
    【解决方案2】:

    当我在属性 UILabel 中使用多种自定义字体时,我也遇到了同样的问题。故事板显示正确的结果,但设备没有!

    我发现如果字体大小与具有不同自定义字体的文本不同。效果很好!!

    所以现在我使用的字体大小略有不同。就像如果一个是 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">
    

    但我仍然无法找到它发生的原因!

    【讨论】:

    • 尝试更改文本对齐方式。就我而言,当我将其更改为 left 而不是 justified 时它起作用了
    • 在 Xcode 10 上为我添加 .01 到文本字体大小.. :(
    【解决方案3】:

    我做什么:

    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
    

    这将应用新的字体颜色以及字体本身。我有一个必须能够包含不同字体的 UILabel。它可以是标题或副标题。因此,当我确定 Label 将包含什么内容时,我必须应用字体。

    【讨论】:

    • 我会试试这个。 1-这样做,我可以通过情节提要设置.text吗? 2-如果 UITextview 包含多个自定义字体,我该如何使用您的代码来管理它?再次感谢!
    • 我个人不知道我可以通过情节提要做到这一点。但是,如果您想要一个具有多种字体的字符串。我认为您必须将字符串拆分为多个可变字符串,然后将它们附加在一起:appendAttributedString。至少这似乎是最容易做的事情。
    • 仍然没有建议使用故事板让它工作?
    • 我假设以下方法不起作用:stackoverflow.com/a/25892126/1235505。关于我在你之前的评论之前的评论。 appendAttributedString 不是必需的。您可以将字体应用于特定范围。原谅我没有早点意识到。可能比 appendAttributedString 性能更好。
    【解决方案4】:

    您是否确保“Futura Book BT”作为自定义字体正确添加到您的应用中?

    【讨论】:

    • 是的。我绝对确定。 :)
    【解决方案5】:

    在我的情况下,问题是我的系统上没有安装字体,所以我用 Font Book 安装了。 然后,字体出现在属性文本标签的列表中。

    编辑:现在我在显示当前文本时遇到了一些问题,我这样做了(我使用的是 UILabel,未在 UITextView 上测试):

    我的解决方案是从 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
            }
        }
    }
    

    然后我做的是这样的:

    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
    

    这样做的一个好处是我现在可以在字符串中放入一些“%s”文本,以便用单词/数字/等进行解析。并且更容易翻译和解析。对于格式化的文本,我必须编写一堆代码来查找文本,应用格式而不触及任何周围的东西。这对我来说效果很好:)

    【讨论】:

    • 这将使字体显示在 IB 中。但是当你实际运行你的应用程序时,并没有使用字体。
    • 是的,我现在已经到了这一点。曾经可以工作,现在似乎无法正常工作……欢呼! :D 我会用我的修复来编辑我的答案。
    【解决方案6】:

    请在 viewDidLayoutSubviews 方法中调用所有代码! 比工作。 在更改字体大小、样式 i viewDidLoad 或 viewWillApperar 方法时,我遇到了很多问题。

    所以只需在 viewDidLayoutSubviews 方法中移动您的代码。您可以使用 flag 只更改一次字体,因为此方法可以多次调用:]

    【讨论】:

      【解决方案7】:

      您可以使用此扩展程序

      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
          }
      }
      

      如何使用扩展程序

      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
      

      因此,整个字符串字体设置为 'Helvetica' 大小为 18,'custom font' 文本设置为 'Arial' 字体大小为 15。

      【讨论】:

        【解决方案8】:

        从情节提要中使 UITextview “可选择”将起作用。

        【讨论】:

          【解决方案9】:

          ✅已修复:

          通过将我的UITextView 子类化为KMPlaceholderTextView 进行修复,这对于向文本视图添加占位符也很有用,并且可以像UITextField 一样在Interface Builder 中使用。

          现在我可以成功使用自定义字体并添加占位符文本了。

          【讨论】:

            【解决方案10】:

            有一个解决方法。只需双击字体文件(在 Finder 中)并将其安装到系统中。

            【讨论】:

              【解决方案11】:

              我使用了不同的字体大小,但仍然遇到问题。然后我将文本对齐方式更改为左对齐而不是对齐。然后效果很好。

              【讨论】:

                猜你喜欢
                • 2016-09-04
                • 1970-01-01
                • 1970-01-01
                • 2015-10-17
                • 1970-01-01
                • 2012-11-27
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多