Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newline (\n) not working in swift

Tags:

string

ios

swift

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.

like image 624
Michael Jaison Avatar asked Jan 28 '16 05:01

Michael Jaison


1 Answers

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

like image 180
Syed Qamar Abbas Avatar answered Sep 22 '22 21:09

Syed Qamar Abbas