I am working on my first iOS application with swift. I need to show some details in UILabel with Newline(\n). Its working good when I assign directly like below
myLabel.text = "\nSome \n\n Text here\n"
Since I need to store the text, I stored it as core data and retrieving as String.
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)
}
But when I set fee as label text, Newline is not working.
myLabel.text = fee
What can I do to make this right?
Thanks in advance.
When you save a text with \n
in local database using coredata or sqlite.
It automatically set another backslash additionally.
Thus when u fetch the string and try to print it just shows the way you have save it.
Just use this line to show multiline text in label.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With