Skip to content

0x04c-Swiftui中NSAttributedString中文乱码问题

解决方案: 需要显式指定编码:.characterEncoding: String.Encoding.utf8.rawValue

代码参考:

swift
@available(iOS 15, *)
@ViewBuilder
func renderHtmlContent() -> some View {
	if let nsAttributedString = try? NSAttributedString(data: Data(noticeText.utf8), options: [
		.documentType: NSAttributedString.DocumentType.html,
		// 不加能会中文乱码
		.characterEncoding: String.Encoding.utf8.rawValue
	],
	documentAttributes: nil),
		let attributedString = try? AttributedString(nsAttributedString, including: \.uiKit)
	{
		VStack(spacing: 0) {
			Text(attributedString)
				.lineLimit((isCaculateByFrameHeight || loadAllContent) ? nil : numberLimit)
				.font(Font.tz_font28)
				.frame(maxHeight: isCaculateByFrameHeight ? (loadAllContent ? .infinity : visibleHeight - 60) : .infinity)
				.lineSpacing(4)
				.foregroundColor(Color(red: 0.15, green: 0.15, blue: 0.15))
				.padding([.leading, .trailing], 2)
				.padding(.top, 16)
				.padding(.bottom, loadAllContent ? 12 : 0)

			if !loadAllContent {
				Button {
					withAnimation {
						loadAllContent = true
					}
				} label: {
					HStack {
						Spacer()
						Text("展示更多").foregroundColor(Color.tz_themeColor)
						Image(podAssetName: "ins-more").frame(width: 9, height: 9)
						Spacer()
					}.padding(12)
				}
			}
		}
	} else {
		renderWebviewContent()
	}
}
@available(iOS 15, *)
@ViewBuilder
func renderHtmlContent() -> some View {
	if let nsAttributedString = try? NSAttributedString(data: Data(noticeText.utf8), options: [
		.documentType: NSAttributedString.DocumentType.html,
		// 不加能会中文乱码
		.characterEncoding: String.Encoding.utf8.rawValue
	],
	documentAttributes: nil),
		let attributedString = try? AttributedString(nsAttributedString, including: \.uiKit)
	{
		VStack(spacing: 0) {
			Text(attributedString)
				.lineLimit((isCaculateByFrameHeight || loadAllContent) ? nil : numberLimit)
				.font(Font.tz_font28)
				.frame(maxHeight: isCaculateByFrameHeight ? (loadAllContent ? .infinity : visibleHeight - 60) : .infinity)
				.lineSpacing(4)
				.foregroundColor(Color(red: 0.15, green: 0.15, blue: 0.15))
				.padding([.leading, .trailing], 2)
				.padding(.top, 16)
				.padding(.bottom, loadAllContent ? 12 : 0)

			if !loadAllContent {
				Button {
					withAnimation {
						loadAllContent = true
					}
				} label: {
					HStack {
						Spacer()
						Text("展示更多").foregroundColor(Color.tz_themeColor)
						Image(podAssetName: "ins-more").frame(width: 9, height: 9)
						Spacer()
					}.padding(12)
				}
			}
		}
	} else {
		renderWebviewContent()
	}
}