【发布时间】:2020-04-24 15:30:18
【问题描述】:
我有以下代码为UITextView 中的字符串创建超链接
extension UITextView {
func setAttributed(text: String) {
self.attributedText = text.htmlAttributedString()
}
}
extension String {
func htmlAttributedString(document: NSAttributedString.DocumentType = .html) -> NSAttributedString? {
guard let data = self.data(using: .utf16, allowLossyConversion: false), let font = font else { return nil }
do {
return try NSMutableAttributedString(data: data, options: [.documentType: document, .characterEncoding: String.Encoding.utf16.rawValue], documentAttributes: nil)
} catch {
debugger("error in string conversion. \(error.localizedDescription)")
return nil
}
}
它的调用如下:self.messageTextView.setAttributed(text: "<a href=\"\(utf16_str1)\">\(utf16_str2)</a>")
text 仅包含简单的 utf8 字符并返回以下结果时工作正常:
text {
NSColor = "kCGColorSpaceModelRGB 0 0 0.933333 1 ";
NSFont = "<UICTFont: 0x1056bd910> font-family: \"Times New Roman\"; font-weight: normal; font-style: normal; font-size: 12.00pt";
NSKern = 0;
NSLink = "https://google.com";
NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 15/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (\n), Lists (\n), BaseWritingDirection 0, HyphenationFactor 0, TighteningForTruncation NO, HeaderLevel 0 LineBreakStrategy 0";
NSStrokeColor = "kCGColorSpaceModelRGB 0 0 0.933333 1 ";
NSStrokeWidth = 0;
NSUnderline = 1;
}
但是,当text 包含ä 或ö 等utf16 字符时,结果如下所示:
<a href="https://google.com">textäö</a>{
NSFont = "<UICTFont: 0x109f0eb30> font-family: \".SFUI-Regular\"; font-weight: normal; font-style: normal; font-size: 12.00pt";
}
我该如何解决这个问题,以使带有 ä 等字符的字符串不会破坏结果
【问题讨论】:
-
在将字符串转换为数据时应该使用 utf8。它永远不会失败。
NSMutableAttributedString(data: Data(utf8),...stackoverflow.com/a/28132610/2303865 -
@LeoDabus 使用
utf8会产生奇怪的字符而不是原始字符。utf16在UILabel上使用时效果很好 -
你是在用它来发出异步请求吗?
-
@LeoDabus 不,它用于在不同页面上显示芬兰语文本。内容是从服务器获取的。
-
显示您如何获取内容、返回的数据是什么以及如何设置属性文本
标签: ios swift uitextview nsattributedstring