【发布时间】:2018-04-03 09:23:43
【问题描述】:
我在UILabel 上使用字距调整属性来显示带有一些自定义字母间距的文本。不幸的是,当我显示用户生成的字符串时,我有时会看到如下内容:
即有时某些表情符号字符不显示。
如果我注释掉字距调整但应用了一些段落样式,我会得到相同类型的错误渲染。
我在文档中找不到任何明确拒绝支持特殊 unicode 字符的内容。我做错了什么还是 iOS 错误?
重现该错误的代码可在此处作为游乐场使用:https://github.com/Bootstragram/Playgrounds/tree/master/LabelWithEmoji.playground
并复制到这里:
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
extension NSAttributedString {
static func kernedSpacedText(_ text: String,
letterSpacing: CGFloat = 0.0,
lineHeight: CGFloat? = nil) -> NSAttributedString {
// TODO add the font attribute
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(NSAttributedStringKey.kern,
value: letterSpacing,
range: NSRange(location: 0, length: text.count))
if let lineHeight = lineHeight {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineHeight
attributedString.addAttribute(NSAttributedStringKey.paragraphStyle,
value: paragraphStyle,
range: NSRange(location: 0, length: text.count))
}
return attributedString
}
}
//for familyName in UIFont.familyNames {
// for fontName in UIFont.fontNames(forFamilyName: familyName) {
// print(fontName)
// }
//}
class MyViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
let myString = "1⚽????????⚾️????????♂️????\n2 ???????????? ????"
let label = UILabel()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 100)
label.attributedText = NSAttributedString.kernedSpacedText(myString)
label.numberOfLines = 0
label.textColor = .black
view.addSubview(label)
self.view = view
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
谢谢。
【问题讨论】:
-
代码示例和您的屏幕截图是否匹配?它将拇指向上的表情符号变成了这两个?
-
你的问题可能是这样的:
NSRange(location: 0, length: text.count)。 Swift 的字符串计数使用扩展的字形簇。 NSAttributedString 使用 ObjC 的编码,即 UTF-16。尝试将其更改为text.utf16.count -
@Larme 他们是。
-
@CodeDifferent:好主意。我没想过检查 ObjC 的编码是什么。它似乎可以解决问题。您为什么不提交您的评论作为答案? :)
-
@CodeDifferent 完全一样,谢谢
标签: ios swift unicode nsattributedstring