SwiftUI:对齐文本 [英] SwiftUI: Justify Text

查看:20
本文介绍了SwiftUI:对齐文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 UIKit 中,可以选择对齐文本,使其看起来像在报纸上.但是,我在 Textelement 上的 SwiftUI 中找不到此选项.我只发现多行对齐与 .trailing、.leading、.center.

In UIKit there is the option to justify text so that it looks like in a newspaper. However I can not find this option in SwiftUI on Textelement. I only found multiline alignment with .trailing, .leading, .center.

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

Can someone point me in the right direction?

推荐答案

SwiftUI 尚不支持对齐文本,因此您必须使用 UIViewRepresentable.因此,对于对齐的文本,您可以包装 UITextView.它看起来像这样:

SwiftUI doesn't yet support justified text, so you'll have to wrap a UIKit view with UIViewRepresentable. So, for justified text, you could wrap UITextView. It would look something like this:

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
    }
}

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

And from here, you can use it in your views like this:

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)
    }
}

这篇关于SwiftUI:对齐文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆