0

I am trying to add letter spacing on a particular text. Big text coming from the server with HTML tags and I need letter spacing only where is P tag. but other than letter-spacing everything works. Am I missing something? Is there a way of doing this with attributed text, or will this need to be resolved with another solution? I currently have tried the following as an example:

let htmlCSSString = "<style>" +
            "html *" +
            "{" +
            "font-size: 15px !important;" +
            "font-family: Arial !important;" +
            "text-align: justify;" +
            "line-height: 1.5;" +
            "text-justify: distribute;" +
            "}" +
            "p" +
            "{" +
            "font-size: 15px !important;" +
            "font-family:  Chap-Semibold !important;" +
            "letter-spacing: 2.6px;" +
            "color: white;" +
            "text-align: center;" +
        "}</style> \(text)" 

        guard let data = htmlCSSString.data(using: .utf8) else { return  }

         do {

  let attributedStr =  try NSMutableAttributedString(data: data,  options: [.documentType: NSMutableAttributedString.DocumentType.html,  .characterEncoding: String.Encoding.utf8.rawValue],documentAttributes: nil)


  lb_details.attributedText = attributedStr
}

I can't use NSAttributedString.Key.kern because I don't know range of text.. and can anyone please explain why only letter-spacing is not working?

Archana
  • 11
  • 2

1 Answers1

0

you can set character spacing using NSAttributedString.Key.kern

let attbStr = NSMutableAttributedString(string: "YOUR_STRING")
attbStr.addAttribute(NSAttributedString.Key.kern, value: 10/*SET_SPACING_VALUE*/, range: NSMakeRange(0, attbStr.length - 1))
YOUR_TEXT_LABEL.attributedText = attbStr

you can find ranges of desired substrings : How to get range of substring in swift3?

SM Abu Taher Asif
  • 2,221
  • 1
  • 12
  • 14
  • Thanks but it's a big text where I don't know the range of text – Archana Aug 12 '20 at 07:15
  • in the answer I have used range NSMakeRange(0, attbStr.length - 1) assuming that you need to set space for all the letters. – SM Abu Taher Asif Aug 12 '20 at 07:21
  • you can find ranges of desired substrings : https://stackoverflow.com/questions/40328242/how-to-get-range-of-substring-in-swift3 – SM Abu Taher Asif Aug 12 '20 at 07:37
  • I am saying it's the whole big text coming from the server with HTML tags and I need letter spacing only where is P tag. I'll edit this in the question. Why this way it's not working? – Archana Aug 12 '20 at 07:51