多行声明一个 NSString

发布于 2024-12-07 21:43:10 字数 296 浏览 2 评论 0原文

有没有办法在多行中声明 NSString ?我想编写 HTML 代码并将其存储到 NSString 中,并且多行代码将更具可读性。我想做这样的事情:

NSString *html = @"\<html\>"
 + @"\<head\>"
 + @"\<title\>The Title of the web\</title\>"
 + @"\</head\>"
 + @"\<body\>"
[...]

Is there any way to declare a NSString in multiple lines? I want to write HTML code and store it into a NSString, and in multiple lines de code will be more readable. I want to do something like this:

NSString *html = @"\<html\>"
 + @"\<head\>"
 + @"\<title\>The Title of the web\</title\>"
 + @"\</head\>"
 + @"\<body\>"
[...]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

如此安好 2024-12-14 21:43:10

这是一个例子:

NSString *html = [NSString stringWithFormat:@"<html> \n"
                          "<head> \n"
                          "<style type=\"text/css\"> \n"
                          "body {font-family: \"%@\"; font-size: %dpx;}\n"
                          "img {max-width: 300px; width: auto; height: auto;}\n"
                          "</style> \n"
                          "</head> \n"
                          "<body><h1>%@</h1>%@</body> \n"
                          "</html>", @"helvetica", 16, [item objectForKey:@"title"], [item objectForKey:@"content:encoded"]];

This is an example:

NSString *html = [NSString stringWithFormat:@"<html> \n"
                          "<head> \n"
                          "<style type=\"text/css\"> \n"
                          "body {font-family: \"%@\"; font-size: %dpx;}\n"
                          "img {max-width: 300px; width: auto; height: auto;}\n"
                          "</style> \n"
                          "</head> \n"
                          "<body><h1>%@</h1>%@</body> \n"
                          "</html>", @"helvetica", 16, [item objectForKey:@"title"], [item objectForKey:@"content:encoded"]];
紫轩蝶泪 2024-12-14 21:43:10

我知道这是 Objective-C 的问题,但用 Swift 就很容易了:

let multiline = """
first line
second line
without escaping characters
""";

I know it's Objective-C question but it's pretty easy with Swift:

let multiline = """
first line
second line
without escaping characters
""";
九命猫 2024-12-14 21:43:10
NSString * html = @"line1\
line2\
line3\
line4";

并注意每行开头的制表符/空格 - 在这种情况下它们确实很重要。

NSString * html = @"line1\
line2\
line3\
line4";

And beware of tabs/spaces in the beginning of each line - they do count in this case.

〆凄凉。 2024-12-14 21:43:10

创建一个具有多行的 NSString 来模拟从多行文本文件读取的 NSString。

NSString * html = @"line1\n\
line2\n\
line3\n\
line4\n";

最后一行的 \n 由您决定。

Create an NSString with multiple lines to mimic a NSString read from a multi-line text file.

NSString * html = @"line1\n\
line2\n\
line3\n\
line4\n";

A \n on the last line is up to you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文