在HTML中为UILabel属性文本设置字体不起作用

时间:2019-05-22 09:24:25

标签: ios swift uilabel nsattributedstring

带有font-size或在UIFont上设置UILabel的HTML文本会使NSAttributedText无法正确呈现。

extension String {
    var htmlToAttributedLabelString: NSAttributedString? {
        guard let data = NSString(string: self).data(using: String.Encoding.utf8.rawValue) else { return nil }
        do {
            return try NSAttributedString(data: data,
                                          options: [.documentType: NSAttributedString.DocumentType.html,
                                                    .characterEncoding: String.Encoding.utf8.rawValue],
                                          documentAttributes: nil)
        } catch {}
        return nil
    }
}
let lbl = UILabel()
lbl.attributedText = "<span style=\"font-size: 22px\"; Please read the <b>Nomination Guidelines</b> before completing this form.".htmlToAttributedLabelString

这不是粗体显示。如果我尝试将字体手动设置为标签,则会出现相同的问题。该如何解决?

1 个答案:

答案 0 :(得分:1)

在您使用的 public class DataModel { public string grant_type { get; set; } public string client_id { get; set; } public string client_secret { get; set; } } static void Main(string[] args) { try { DataModel dm = new DataModel(); dm.grant_type = "client_credentials"; dm.client_id = "ruban123"; dm.client_secret = "123456"; var credentials = dm.grant_type + dm.client_id + dm.client_secret; #region Http Post string messageUri = "https://sampleurl.apivision.com:8493/abc/oauth/token"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(messageUri); request.Headers.Add("Authorization", "Basic " + credentials); request.ContentType = "application/json"; request.Method = "POST"; using (var streamWriter = new StreamWriter(request.GetRequestStream())) { string jsonModel = Newtonsoft.Json.JsonConvert.SerializeObject(dm); streamWriter.Write(jsonModel); streamWriter.Flush(); streamWriter.Close(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); string jsonString = null; using (StreamReader reader = new StreamReader(responseStream)) { jsonString = reader.ReadToEnd(); Console.WriteLine(); reader.Close(); } #endregion Http Post } catch (Exception ex) { } }[API REFERENCE][1] 中,html text标签没有关闭。

尝试将span的值更改为:

lbl.attributedText

输出:

enter image description here