简体   繁体   中英

How can I declare string as with a paragraph with swift?

I want to declare string with p paragraph by swift , like following, but not right, can anyone give me a favor?

I don't want to declare string with one line , which is not easy to read

let format = "<p><strong>%@ paddock selected</strong></p>
                        <p>Total Area %.1f ha</p>
                        <p>Effective Area %.1f ha</p>
                        <p></p>
                        <p><strong>%@</strong></p>
                        <p>Total Area %.1f ha</p>
                        <p>Effective Area %.1f ha</p>"

And I don't want somethings like following, I have to add " at leading and " + and trailing :(

let format = "<style>" +
                        "p {" +
                        "    margin: 1 1 1 1;" +
                        "}" +
                        "</style>" +
                        "<body>" +
                        "<p><strong>%@ paddock selected</strong></p>" +
                        "<p>Total Area %.1f ha</p>" +
                        "<p>Effective Area %.1f ha</p>" +
                        "<p></p>" +
                        "<p><strong>%@</strong></p>" +
                        "<p>Total Area %.1f ha</p>" +
                        "<p>Effective Area %.1f ha</p>" +
                        "</body>"

With objective-c , I just need to add \\ each line will be ok, but not well in swift

NSString* format = @"<p><strong>%@ paddock selected</strong></p>\
                        <p>Total Area %.1f ha</p>\
                        <p>Effective Area %.1f ha</p>\
                        <p></p>\
                        <p><strong>%@</strong></p>\
                        <p>Total Area %.1f ha</p>\
                        <p>Effective Area %.1f ha</p>";

Swift lacks this feature. It has neither autoconcatenation of string literals nor here documents. File a bug report if it's important to you.

What I do is load big strings, including format strings, as a text file from the app bundle.

You can use the multiline format into Localizable.strings (which also is the right place where to write strings).

在此处输入图片说明

Please note that this method will actually add newline instructions at the end of each line! However this should not be a problem in your case since you are writing HTML.

More

This is not directly related to your question, however you could also find useful this String extension

extension String {
    var localized: String {
        return NSLocalizedString(self, comment: "")
    }
}

since it does allow you to retrieve the localized version of your string simply writing

"Test".localized

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM