我试图在UITextView中使用unicode字符U + 00AE。如果我使用下面的代码\u{00AE}
:
textView.text = "THING AND STUFF TrademarkedThing\u{00AE}"
但是,如果我从其他位置提取一些文本(这在技术上来自API调用,但这不重要),并将其分配给textView,我不会得到unicode字符:
var apiText = "TrademarkedThing\u{00AE}" //Pulled from API call as text and saved into text variable
textView.text = "THING AND STUFF " + apiText
所以在下面的代码中,第一个unicode字符没有显示,但是第二个unicode字符显示。
var apiText = "TrademarkedThing\u{00AE}" //Pulled from API call as text and saved into text variable
textView.text = "THING AND STUFF " + apiText + " \u{00AE}"
为什么赢得该文字节目中的unicode? p>
答案 0 :(得分:0)
Unicode转换(来自\u{...}
)仅适用于字符串文字。如果比较这两个,你可以看到问题:
let t1 = "Thing\u{00AE}"
// Thing®
let t2 = "Thing\\u{00" + "AE}"
// Thing\u{00AE}
由于你的字符串来自另一个来源,它就像第二个来源一样。 Swift语言书有Unicode characters in string literals部分。
如果你想在事后解释这些Unicode序列,这里有一个String
扩展名:
extension String {
func indexOfSubstring(str: String, fromIndex: String.Index? = nil) -> String.Index? {
var index = fromIndex ?? startIndex
while index < endIndex {
if self[Range(start: index, end: endIndex)].hasPrefix(str) {
return index
}
index = index.successor()
}
return nil
}
func convertedUnicodeSequences() -> String {
if let index = indexOfSubstring("\\u{") {
if let nextIndex = indexOfSubstring("}", fromIndex: index) {
let substr = self[Range(start: advance(index, 3), end: nextIndex)]
let scalar = UnicodeScalar(UInt32(strtoul(substr, nil, 16)))
return self[Range(start: startIndex, end: index)] +
String(scalar) +
self[Range(start: nextIndex.successor(), end: endIndex)].convertedUnicodeSequences()
}
}
return self
}
}