有没有办法像Java的“ \ n”一样快速制作新行?
var example: String = "Hello World \n This is a new line"
有没有办法像Java的“ \ n”一样快速制作新行?
var example: String = "Hello World \n This is a new line"
Answers:
您应该可以\n
在Swift字符串中使用它,并且应该可以按预期工作,从而创建换行符。您将需要在后面删除空格以\n
进行正确的格式化,如下所示:
var example: String = "Hello World \nThis is a new line"
如果将其打印到控制台,则应变为:
Hello World
This is a new line
但是,根据您将如何使用此字符串,还有一些其他注意事项,例如:
\r\n
Windows换行符。编辑:您说您正在使用UITextField,但它不支持多行。您必须使用UITextView。
您可以使用以下代码;
var example: String = "Hello World \r\n This is a new line"
你可以这样做
textView.text = "Name: \(string1) \n" + "Phone Number: \(string2)"
输出将是
名称:string1的输出电话号码:string2的输出
"\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"
可以正常工作。