gpt4 book ai didi

c# - 将简单的 HTML 解析为 NSAttributedString 后设置字体大小不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:17:56 25 4
gpt4 key购买 nike

我想将简单的 HTML 标记解析为 NSAttributedString这样我就可以在 UITextView 上显示格式化文本.我找到了 thisthat在应该容易转换的地方发布。这就是我用过的:

public static NSAttributedString GetAttributedStringFromHtml(string html)
{
NSError error = null;
NSAttributedString attributedString = new NSAttributedString (NSData.FromString(html),
new NSAttributedStringDocumentAttributes{ DocumentType = NSDocumentType.HTML, StringEncoding = NSStringEncoding.UTF8 },
ref error);
return attributedString;
}

到目前为止这是可行的,但现在我想更改字体大小,因为默认字体非常小。

string content = "<strong>I'm strong.</strong><br/>http://www.google.com";

UITextView textView = new UITextView ();
textView.Editable = false;
textView.Font = UIFont.SystemFontOfSize (25);
textView.Text = content;
textView.AttributedText = GetAttributedStringFromHtml (content);
textView.DataDetectorTypes = UIDataDetectorType.Link;
textView.Selectable = true;

上面的代码确实正确解析了它,但字体大小没有改变。我尝试使用 NSMutableAttributedString , 但似乎不需要 NSData作为参数进行解析,如 NSAttributedString做。也许将多个 NSAttributedString 组合起来是一种选择,但我不知道如何。另一种选择是像这个例子一样进行转换:

NSMutableAttributedString attributedString = (NSMutableAttributedString) GetAttributedStringFromHtml (content);
attributedString.AddAttribute (UIStringAttributeKey.Font, UIFont.SystemFontOfSize (25), new NSRange (0, content.Length));
textView.AttributedText = attributedString;

但我得到 System.InvalidCastException .

如何更改 UITextView 的字体大小即使我使用 HTML 解析?

编辑:

现在我尝试创建我的 NSMutableAttributedString :

NSAttributedString parsedString = GetAttributedStringFromHtml (content);
NSMutableAttributedString attributedString = new NSMutableAttributedString (parsedString);
attributedString.AddAttribute (UIStringAttributeKey.Font, UIFont.SystemFontOfSize (17), new NSRange (0, attributedString.Length));
textView.AttributedText = attributedString;

这确实可以编译,字体更大并且 HTML 也被解析,但它忽略了 <strong>例如。文本不是粗体,它应该是粗体。似乎第二个属性覆盖了第一个...

最佳答案

我尝试了一些方法,但都没有用。所以我已经在解析 HTML 为什么不使用内联 CSS 语法呢?

<p style='font-size:17px'><strong>I'm bold.</strong><br/>http://www.google.com</p>

关于c# - 将简单的 HTML 解析为 NSAttributedString 后设置字体大小不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28324358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com