SwiftUI:对齐文本

SwiftUI: Justify Text

在 UIKit 中,有一个选项可以调整文本,使其看起来像在报纸上。但是我在 Textelement 上的 SwiftUI 中找不到这个选项。我只发现与 .trailing, .leading, .center.

的多行对齐

有人能指出我正确的方向吗?

SwiftUI 尚不支持两端对齐的文本,因此您必须使用 UIViewRepresentable. So, for justified text, you could wrap UITextView 包装 UIKit 视图。它看起来像这样:

struct TextView: UIViewRepresentable {
    var text: String
    
    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
        textView.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
        textView.textAlignment = .justified
        return textView
    }
    
    func updateUIView(_ uiView: UITextView, context: Context) {
        uiView.text = text
    }
}

从这里开始,您可以像这样在您的视图中使用它:

struct MyView: View {
    var body: some View {
        TextView(text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin quis elementum lorem. Nullam fermentum viverra ipsum a finibus. Vestibulum venenatis risus vel leo sagittis, id aliquet tortor elementum. Aenean elementum orci ac sapien dictum laoreet. Sed placerat, magna sit amet eleifend auctor, odio ligula dapibus lacus, quis interdum ligula velit at est. Curabitur molestie dui sodales faucibus cursus. Duis posuere ex diam, tempor tincidunt nunc venenatis vitae. Integer vulputate odio vitae enim tincidunt, eget vulputate arcu pulvinar. Integer in magna erat.")
        .frame(width: 500, height: 300)
    }
}