SwiftUI文本的对齐方式

5
有没有人找到一种方法,以两端对齐的方式对Text中的字符串进行对齐?
在我的阅读应用中,我希望为用户提供选择两端对齐的选项,即.leading.trailing都为true。不幸的是,Text.multilineTextAlignment修饰符只有三个选项:.leading.center.trailing
如果没有,我仍然可以将UILabel包装成一个UIViewRepresentable,因为UILabel具有.justified对齐选项,但我认为它也应该在Text中提供,并且我无法找到它。
1个回答

4

我知道我迟到了,但我也遇到了同样的问题,我会在这里写下来,它可能会帮助未来的其他开发者。

不幸的是,截至目前,在SwiftUI 2.0中,Apple仍不支持.justified属性。

您需要依赖于UIKit。

将此代码添加到您的项目中。

   struct LabelAlignment: UIViewRepresentable {
    var text: String
    var textAlignmentStyle : TextAlignmentStyle
    var width: CGFloat

    func makeUIView(context: Context) -> UILabel {
        let label = UILabel()
        label.textAlignment = NSTextAlignment(rawValue: textAlignmentStyle.rawValue)!
        label.numberOfLines = 0
        label.preferredMaxLayoutWidth = width
        label.setContentHuggingPriority(.required, for: .horizontal)
        label.setContentHuggingPriority(.required, for: .vertical)

        return label
    }

    func updateUIView(_ uiView: UILabel, context: Context) {
        uiView.text = text
    }
}

enum TextAlignmentStyle : Int{
     case left = 0 ,center = 1 , right = 2 ,justified = 3 ,natural = 4
}

然后像这样使用它

LabelAlignment(text: "Your text here", textAlignmentStyle: .justified, width: UIScreen.main.bounds.width - 20)

将20更改为任何您喜欢的数字以在左右两侧添加空格。

我的解决方案将取决于文本内容的大小,如果文本很小,则视图将很小,反之亦然,因此它将充当Text()。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接