0

My server return some text contain \n. I expect \n to print a new line but it does not work. Swift just printed the text and \n too. But if I declare string on my local place, e.g.

let test = "This is a \nbook"

It works! Swift and UILabel prints a new line, e.g.

This is a

book

Then my code i set

myLabel.numberOfLines = 0

It doesn't work as expected, but the local variable works.

I don't understand why though.

rjdkolb
  • 10,377
  • 11
  • 69
  • 89

3 Answers3

1

Try this on the string which you get from the server:

saleDescription["description"].string!.replacingOccurrences(of: "\\n", with: "\n")
christopher.online
  • 2,614
  • 3
  • 28
  • 52
-1
myLabel.numberOfLines = -1

Making myLabel numberOfLines = -1 means "infinite" lines. I hope this helps.

Richter B
  • 7
  • 3
  • it's not work. if print or set it on UILabel .it always print "\n" – Sakonlapak Petcharayuttapan Jan 17 '16 at 04:49
  • 1
    @SakonlapakPetcharayuttapan your approach it is correct. To allow multiple lines you need to set it to ZERO https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILabel_Class/#//apple_ref/occ/instp/UILabel/numberOfLines – Leo Dabus Jan 17 '16 at 06:04
  • @SakonlapakPetcharayuttapan make sure your label frame has enough room to display all lines – Leo Dabus Jan 17 '16 at 06:06
  • @LeoDabus I has enough room to show all line. If i receive text from my server .It's always print /n in log and UILabel but if i declare a same text in local place . it works and show a new line for me – Sakonlapak Petcharayuttapan Jan 17 '16 at 06:28
  • @LeoDabus I tried to use that method then my string from server didn't split \n to array but it change \n to \\n in array[0] – Sakonlapak Petcharayuttapan Jan 17 '16 at 06:52
  • @SakonlapakPetcharayuttapan How would you expect someone to help you with such a complex string if you post it in a screenshot – Leo Dabus Jan 17 '16 at 16:04
-1

When you have such a case, use a UITextView instead of UILabel

iosMentalist
  • 3,066
  • 1
  • 30
  • 40
  • For who downvoted, the textview was the only solution for this case. I was getting data from the server and while populating the text in UILabel the \n was not returning. – iosMentalist Oct 19 '17 at 11:22