如何快速换行


79

有没有办法像Java的“ \ n”一样快速制作新行?

var example: String = "Hello World \n This is a new line"

2
这对swift也正确且有效(当然,这取决于您将在何处使用此字符串,在标签标题中,未设置标签属性也可能不会得到多行)。删除下一行之前的空格,然后您将获得所需的内容。
smozgur

您如何打印线?在某种UI中?在CLI上?
David Hoelzer

Answers:


141

您应该可以\n在Swift字符串中使用它,并且应该可以按预期工作,从而创建换行符。您将需要在后面删除空格以\n进行正确的格式化,如下所示:

var example: String = "Hello World \nThis is a new line"

如果将其打印到控制台,则应变为:

Hello World
This is a new line

但是,根据您将如何使用此字符串,还有一些其他注意事项,例如:

  • 如果将其设置为UILabel的text属性,请确保UILabel的numberOfLines = 0,以允许无限行。
  • 在某些网络用例中,请改用\r\nWindows换行符。

编辑:您说您正在使用UITextField,但它不支持多行。您必须使用UITextView。


29

也有用:

let multiLineString = """
                  Line One
                  Line Two
                  Line Three
                  """
  • 使代码更易读
  • 允许复制粘贴


2

你可以这样做

textView.text = "Name: \(string1) \n" + "Phone Number: \(string2)"

输出将是

名称:string1的输出电话号码:string2的输出


2

"\n" 不是到处都在工作!

例如,在电子邮件中,如果您在自定义键盘中使用它,则会在文本中添加确切的“ \ n”而不是新行,例如: textDocumentProxy.insertText("\n")

还有另一个newLine字符可用,但我不能只是简单地将它们粘贴在这里(因为它们会)。

使用此扩展名:

extension CharacterSet {
    var allCharacters: [Character] {
        var result: [Character] = []
        for plane: UInt8 in 0...16 where self.hasMember(inPlane: plane) {
            for unicode in UInt32(plane) << 16 ..< UInt32(plane + 1) << 16 {
                if let uniChar = UnicodeScalar(unicode), self.contains(uniChar) {
                    result.append(Character(uniChar))
                }
            }
        }
        return result
    }
}

您可以访问任何中的所有字符CharacterSet。有一个称为的字符集newlines。使用其中之一来满足您的要求:

let newlines = CharacterSet.newlines.allCharacters
for newLine in newlines {
    print("Hello World \(newLine) This is a new line")
}

然后将您测试过并工作过的产品存储到任何地方,并在任何地方使用。请注意,您无法中继字符集的索引。它可能会改变。

但是大多数时候都 "\n"可以正常工作。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.