在 SwiftUI 中应用段落样式的问题

问题描述 投票:0回答:1

我有一串阿拉伯语和英语单词的文本,我需要使用

NSMutableAttributedString
添加属性并使用
NSMutableParagraphStyle
添加段落样式。问题是段落样式不适用于文本,不知道为什么。首先,我检测阿拉伯字符并更改颜色(它有效),然后尝试更改行间距或对齐方式,但这不起作用。这是代码:

let arabicChars = try? NSRegularExpression(pattern: "[\\u0600-\\u06FF\\u0750-\\u077F\\u08A0-\\u08FF\\uFB50-\\uFDFF\\uFE70-\\uFEFF\\s]+", options: [])
arabicChars?.enumerateMatches(in: pureText, options: [], range: range) { (result, _, _) in
    if let subStringRange = result?.range(at: 0) {
        stringText.addAttribute(.foregroundColor, value: UIColor(.brown), range: subStringRange)
        
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .right
        paragraphStyle.lineSpacing = 1.2
        paragraphStyle.lineHeightMultiple = 1.2
        stringText.addAttribute(.paragraphStyle, value: paragraphStyle, range: subStringRange)
        stringText.addAttribute(.font, value: UIFont(name: "CustomFont", size: 16)!, range: subStringRange)
    }
    }

然后在 SwiftUI 中使用该函数,如下所示:

    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 15) {
                Text(word.word?.capitalized ?? "")
                    .font(.system(size: 32, weight: .bold, design: .serif))
            
                Text(AttributedString(applyAttributedStyle(word.meaning)))
            }
            .frame(maxWidth: .infinity, alignment: .leading)
        }
        .padding(.horizontal)
    }
}

这是显示当前结果(左)与右结果的图像:

编辑1: 它与 UIKit 的 UITextView 配合良好,但不适用于 SwiftUI 的 Text

编辑2: 我已经使用

UIViewRepresentable
UITextView

解决了这个问题
ios swift swiftui nsmutableattributedstring nsmutableparagraphstyle
1个回答
0
投票

之所以如此,是因为 SwiftUI

Text
视图不支持所有
AttributedString
属性。

特别的,它只支持

AttributeScopes.SwiftUIAttributes
中定义的属性,不包括
.paragraphStyle

目前唯一的解决方案是使用 UIKit/AppKit,正如您自己发现的那样。

这是一些有用的背景阅读:https://dimillian.medium.com/swiftui-attributedstring-is-not-there-yet-63d49e9f9c16

© www.soinside.com 2019 - 2024. All rights reserved.