我怎么能在多行分割字符串,如下面?
var text:String = "This is some text
over multiple lines"
我怎么能在多行分割字符串,如下面?
var text:String = "This is some text
over multiple lines"
当前回答
Swift 4通过提供多行字符串文字支持解决了这个问题。要开始字符串字面量,添加三个双引号(" " " ")并按回车键,按回车键后开始写带有任何变量的字符串,换行符和双引号,就像你在记事本或任何文本编辑器中写的那样。要结束多行字符串文字再次写入(" " ")在新行。
参见下面的例子
let multiLineStringLiteral = """
This is one of the best feature add in Swift 4
It let’s you write “Double Quotes” without any escaping
and new lines without need of “\n”
"""
print(multiLineStringLiteral)
其他回答
Swift 4支持多行字符串字面值。除了换行符,它们还可以包含未转义的引号。
var text = """
This is some text
over multiple lines
"""
旧版本的Swift不允许你在多行上有一个字面值,但你可以在多行上添加字面值:
var text = "This is some text\n"
+ "over multiple lines\n"
另一种方法是,如果你想使用带有预定义文本的字符串变量,
var textFieldData:String = "John"
myTextField.text = NSString(format: "Hello User, \n %@",textFieldData) as String
myTextField.numberOfLines = 0
一种方法是将标签文本设置为attributedText,并更新字符串变量以包含换行符的HTML (<br />)。
例如:
var text:String = "This is some text<br />over multiple lines"
label.attributedText = text
输出:
This is some text
over multiple lines
希望这能有所帮助!
下面是一个代码片段,用n个字符分隔字符串:
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let str = String(charsPerLine: 5, "Hello World!")
print(str) // "Hello\n Worl\nd!\n"
}
}
extension String {
init(charsPerLine:Int, _ str:String){
self = ""
var idx = 0
for char in str {
self += "\(char)"
idx = idx + 1
if idx == charsPerLine {
self += "\n"
idx = 0
}
}
}
}
我尝试了几种方法,但找到了一个更好的解决方案: 只需使用“文本视图”元素。它的文本自动显示多行! 找到这里:UITextField多行