【问题标题】:NSAttributedString change color and font sizeNSAttributedString 改变颜色和字体大小
【发布时间】:2020-01-28 11:15:58
【问题描述】:

大家好,我有一个小问题,我正在使用 func:

static func convertFromHTMLString(_ input: String?) -> NSAttributedString? {

        guard let input = input else { return nil }

        guard let data = input.data(using: String.Encoding.unicode, allowLossyConversion: true) else { return nil  }
        return try? NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html], documentAttributes: nil)
    }

从 Localizable.strings 中读取我的字符串,属性如下:

但是当我运行我的应用程序时,它看起来:

这会将我的标签颜色更改为黑色,字体大小更改为 10-12 ;/ 我的标签应该是白色,字体大小为 17,有人知道如何解决吗? 谢谢 ! :)

@Edit1 解决方案必须如下所示 这就是它在 Android 上的外观。

【问题讨论】:

    标签: html swift string nsattributedstring


    【解决方案1】:
    func convertFromHTMLString(_ input: String?) -> NSAttributedString? {
    
        guard let input = input else { return nil }
    
        guard let data = input.data(using: String.Encoding.unicode, allowLossyConversion: true) else { return nil  }
    
    
        if let string = try? NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html], documentAttributes: nil).string
        {
            //Set color and font
            let myAttribute = [ NSAttributedString.Key.foregroundColor: UIColor.white , NSAttributedString.Key.font: UIFont(name: "Chalkduster", size: 17.0)!  ]
            let myAttrString = NSAttributedString(string: string, attributes: myAttribute)
            return myAttrString
        }
    
    
        return nil
    }
    

    【讨论】:

    • 它改变颜色和字体大小,但现在不工作 这对我来说最重要 ;/
    • 向我发送类似文本的示例 html
    • 您之前已经询问过 并且被标记为重复。您是否尝试过链接问题中的答案?
    • @Szczowio 我试试这个 var html = "\n Nowy wspabiay swiat
      \n Aldous Huxley

      \n Exampleeee " 工作正常
    • @koen 是的。我从你链接我的懒惰问题中意识到了答案,但现在我遇到了这个问题,我试图在互联网、论坛、Facebook 中找到解决方案,但什么都没有;o 这对我来说找到解决方案非常重要。 #Stefan 我不能把它放到 var 中,因为我有 500 个字符串,这就是为什么我必须在 Localizable.strings 中使用它,当我尝试将它放在 var 上时它仍然可以正常工作并剪切我的字符串我没有知道为什么;/#Edit1 我添加了它在我的 Android 项目的解决方案中的外观,在 iOS 上我必须看起来一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 2013-03-23
    相关资源
    最近更新 更多