我正在使用 swift 开发我的第一个 iOS 应用程序。我需要用换行符(\n)在 UILabel 中显示一些详细信息。当我直接分配时效果很好,如下所示
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
我能做些什么来纠正这个问题?
提前致谢。
当您保存文本时\n
使用 coredata 或 sqlite 在本地数据库中。
它会自动另外设置另一个反斜杠。
因此,当您获取字符串并尝试打印它时,只会显示您保存它的方式。
只需使用此行即可在标签中显示多行文本。
斯威夫特2.0
let fee = person.valueForKey("fee") as? String
let newText = fee?.stringByReplacingOccurrencesOfString("\\n", withString: "\n")
myLabel.text = newText
斯威夫特3.0
guard let fee = person.valueForKey("fee") as? String else {return}
let newText = fee.replacingOccurrences(of: "\\n", with: "\n")
myLabel.text = newText
不要忘记通过设置行数 = 0 来允许 UILabel 对象显示无限行
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)