我怎么能在多行分割字符串,如下面?
var text:String = "This is some text
over multiple lines"
我怎么能在多行分割字符串,如下面?
var text:String = "This is some text
over multiple lines"
当前回答
一种方法是将标签文本设置为attributedText,并更新字符串变量以包含换行符的HTML (<br />)。
例如:
var text:String = "This is some text<br />over multiple lines"
label.attributedText = text
输出:
This is some text
over multiple lines
希望这能有所帮助!
其他回答
下面的例子描述了一个多行连续,使用圆括号作为一个简单的解决方法,以解决Xcode 6.2 Beta版本的Swift错误,它抱怨表达式太复杂,无法在合理的时间内解析,并考虑将其分解为更小的片段:
.
.
.
return String(format:"\n" +
(" part1: %d\n" +
" part2: %d\n" +
" part3: \"%@\"\n" +
" part4: \"%@\"\n" +
" part5: \"%@\"\n" +
" part6: \"%@\"\n") +
(" part7: \"%@\"\n" +
" part8: \"%@\"\n" +
" part9: \"%@\"\n" +
" part10: \"%@\"\n" +
" part12: \"%@\"\n") +
" part13: %f\n" +
" part14: %f\n\n",
part1, part2, part3, part4, part5, part6, part7, part8,
part9, part10, part11, part12, part13, part14)
.
.
.
样本
var yourString = "first line \n second line \n third line"
以防您发现+运算符不合适
正如litso所指出的,在一个表达式中重复使用+-操作符会导致Xcode Beta挂起(刚刚用Xcode 6 Beta 5检查过):Xcode 6 Beta无法编译
目前,多行字符串的另一种替代方法是使用一个字符串数组,并将其压缩为+:
var text = ["This is some text ",
"over multiple lines"].reduce("", +)
或者,可以更简单地使用join:
var text = "".join(["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
}
}
}
}
一种方法是将标签文本设置为attributedText,并更新字符串变量以包含换行符的HTML (<br />)。
例如:
var text:String = "This is some text<br />over multiple lines"
label.attributedText = text
输出:
This is some text
over multiple lines
希望这能有所帮助!