1

I am trying to add 2 white space at the last position of a string but when I set this in a label I found no space. But if I added 2 white space with another character, it works ok. Then I tried to add 2 white space with some extra character and then trim these extra characters. But for all these case I observed no space when I placed this in a text label. I am trying this for the right alignment.

let name: String = self.cityModelArr[indexPos].countryShortName+"  12"
let endIndex = name.index(name.endIndex, offsetBy: -2)
let truncated = String(name[..<endIndex])
self.testLabel.text = truncated

I have tried some more solutions from the internet but failed to achieve my goal.

Sohail Ahmad
  • 7,309
  • 5
  • 27
  • 46
spectre_d2
  • 193
  • 15

4 Answers4

0

It's totally normal, the label removes the spaces when you preview it on screen.

You can avoid this using a ZERO WIDTH NON-JOINER character (U+200C), like in this case:

label = "Here I want a space:  \u{200c}"
Riki95
  • 706
  • 1
  • 7
  • 16
  • I had also tried this solution and result was same. let name: String = self.cityModelArr[indexPos].countryShortName+" \u{200c}" self.testLabel.text = name – spectre_d2 Feb 12 '20 at 12:52
0

There is no need to right too much code for that

  let name: String = self.cityModelArr[indexPos].countryShortName+"  12"
  let endIndex = name.index(name.endIndex, offsetBy: -2)
   let truncated = String(name[..<endIndex])
   self.testLabel.text = truncated

only you need that code:-

   let name: String = "your string" + String(repeating: " ", count: 2)//Your Space count like your want 2
   self.testLabel.text = name
   Response:-  "your string  "
Vipin Pareek
  • 236
  • 2
  • 10
0

You may use \t at end of string to add space.

self.testLabel.text = "\(self.cityModelArr[indexPos].countryShortName)\t"
Neethu M
  • 644
  • 6
  • 11
0

You can define your string like

let strData = "This is testing string" 

 self.lblText.text = "\(strData) "
Ketan Sodvadiya
  • 464
  • 5
  • 11