问题描述
我正在尝试在特定文本上添加字母间距。来自服务器的带有HTML标签的大文本,我只需要在P标签所在的位置使用字母间距。但是除了字母间隔之外,其他所有功能都可以使用。我想念什么吗?是否可以使用属性文本来完成此操作,还是需要使用其他解决方案来解决? 我目前已尝试以下示例:
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
}
我不能使用NSAttributedString.Key.kern,因为我不知道文本范围。.任何人都可以解释为什么仅字母间距不起作用吗?
解决方法
您可以使用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
您可以找到所需子字符串的范围:How to get range of substring in swift3?