我正在使用 swift 开发我的第一个 iOS 应用程序。我需要在 UILabel 中使用换行符 (\n) 显示一些细节。当我像下面这样直接分配时它工作得很好
myLabel.text = "\nSome \n\n Text here\n"
因为我需要存储文本,所以我将其存储为核心数据并以字符串形式检索。
let context: NSManagedObjectContext = appDel.managedObjectContext
let fetchRequest = NSFetchRequest()
let entityDescription = NSEntityDescription.entityForName("Details", inManagedObjectContext: context)
fetchRequest.entity = entityDescription
do {
let result = try context.executeFetchRequest(fetchRequest)
print(result.count)
if (result.count > 0) {
for i in 0..<result.count
{
let person = result[i] as! NSManagedObject
fee = person.valueForKey("fee") as! String
content = person.valueForKey("content") as! String
pattern = person.valueForKey("pattern") as! String
documentation = person.valueForKey("documentation") as! String
}
}
} catch {
let fetchError = error as NSError
print(fetchError)
}
但是当我将费用设置为标签文本时,换行不起作用。
myLabel.text = fee
我该怎么做才能做到这一点?
提前致谢。
最佳答案
当您使用 coredata 或 sqlite 在本地数据库中保存带有 \n
的文本时。
它会自动另外设置另一个反斜杠。
因此,当您获取字符串并尝试打印它时,它只会显示您保存它的方式。
只需使用此行即可在标签中显示多行文本。
swift 2.0
let fee = person.valueForKey("fee") as? String
let newText = fee?.stringByReplacingOccurrencesOfString("\\n", withString: "\n")
myLabel.text = newText
swift 3.0
guard let fee = person.valueForKey("fee") as? String else {return}
let newText = fee.replacingOccurrences(of: "\\n", with: "\n")
myLabel.text = newText
Don't forget to allow UILabel object to show infinite line by setting number of lines = 0
关于ios - 换行符(\n)不能快速工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35053698/