【问题标题】:How to style the NSString using CSS?如何使用 CSS 设置 NSString 样式?
【发布时间】:2015-05-07 01:27:26
【问题描述】:

我有一个使用数据库的字典项目。我想对结果进行样式设置,以便它可以分隔线、具有不同的颜色等。

例子:

Song ///这行将是蓝色,带有强文本
N. // 这行将是黑色,带有强文本
うた //这条线是正常的灰色

在 Objective-C 中很难将每个都放入标签中。我想知道是否可以使用 CSS 进行样式设置?

【问题讨论】:

  • NSAttributedString 怎么样?
  • NSAttributedString, UIWebView?
  • 哦,只要我和web无关,我不使用UIWebview。
  • 我什至不确定您是否需要 UIWebView... NSAttributedString 的 initWithHtml 应该可以完成 - 您可以使用 UILabel 的属性文本属性
  • 你有什么教程可以教我吗?

标签: css objective-c nsstring


【解决方案1】:

你可以这样使用:

NSString *htmlTemplate = 
    @"<html>\n"
    "<head>\n"
    "<style type=\"text/css\">\n"
        "h4 {\n"
        "text-transform: uppercase;\n"
        "margin-bottom: 5px;\n"
        "font-family: HelveticaNeue;\n"
        "font-size: 18px;\n"
        "color: #212121;\n"
        "font-weight: bold;\n"
        "line-height: 1.1;\n"
        "text-align: center;\n"
        "margin-bottom: 15px\n"
    "}\n"
    "p {\n"
        "text-align: center;\n"
        "color: #757575;\n"
        "line-height: 1.2;\n"
        "font-family: Helvetica;\n"
        "font-size: 18px;\n"
    "}\n"
    "</style>\n"
    "</head>\n"
    "<body>\n"
    "%@\n"
    "</body>\n"
    "</html>";

NSString *text = @"<h4>This is a test</h4><p>Testing CSS styled text with Objective-C</p>";

myLabel.attributedText = [[NSAttributedString alloc]
                            initWithData:[[NSString stringWithFormat:htmlTemplate, text] dataUsingEncoding:NSUTF8StringEncoding]
                            options:@{ NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType }
                            documentAttributes:nil
                            error:nil];

这只是一个示例,您可以根据需要在模板中添加更多 HTML 和换行符。

【讨论】:

  • 您好,谢谢您,看起来很有趣。但是我应该将它与 UIwebView 一起使用吗?
  • 不,将它与任何 UILabel 对象一起使用。
  • 你很酷!几乎就在那里--->我收到错误消息说:在“NSSString”类型的对象上找不到属性“attributedText”
  • 确保在“UILabel”对象上设置“attributedText”。听起来您将其设置在“NSString”对象上。
  • 你太棒了!! Juan --> 我想知道 ErasmoOliveira 怎么样,他说这是不可能的并且会结束我的问题->你在哪里?你能看看这个吗?天哪,他走了!!没有足够教育的坏人总是很粗鲁--->好人保持冷静并给出解决方案!我能看到
【解决方案2】:

在UIWebView 中显示您的内容并使用捆绑的 CSS 文件。

【讨论】:

  • 哦,我跟web没关系,我不能用这个方法。我想我需要在数据库中添加更多列才能在objective-c的标签中显示它:(
猜你喜欢
  • 2016-07-30
  • 2013-12-11
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多