我怎么能在多行分割字符串,如下面?

var text:String = "This is some text
                   over multiple lines"

当前回答

另一种方法是,如果你想使用带有预定义文本的字符串变量,

var textFieldData:String = "John"
myTextField.text = NSString(format: "Hello User, \n %@",textFieldData) as String
myTextField.numberOfLines = 0

其他回答

加上@Connor的回答,也需要有\n。以下是修改后的代码:

var text:String = "This is some text \n" +
                  "over multiple lines"

Swift 4支持多行字符串字面值。除了换行符,它们还可以包含未转义的引号。

var text = """
    This is some text
    over multiple lines
    """

旧版本的Swift不允许你在多行上有一个字面值,但你可以在多行上添加字面值:

var text = "This is some text\n"
         + "over multiple lines\n"

下面是一个简单的实现(Swift 5.4+),使用resultBuilder来清理语法!

@resultBuilder
public struct StringBuilder {
    public static func buildBlock(_ components: String...) -> String {
        return components.reduce("", +)
    }
}

public extension String {
    init(@StringBuilder _ builder: () -> String) {
        self.init(builder())
    }
}

用法:

String {
    "Hello "
    "world!"
} 
// "Hello world!"

一种方法是将标签文本设置为attributedText,并更新字符串变量以包含换行符的HTML (<br />)。

例如:

var text:String = "This is some text<br />over multiple lines"
label.attributedText = text

输出:

This is some text
over multiple lines

希望这能有所帮助!

你可以使用unicode equals for enter或\n并在你的字符串中实现它们。例如:\u{0085}。