SwiftUI中文本对齐的几种情况


1个月前 102次点击 来自 移动端

标签: SwiftUI

原文链接:How to align text center/leading/trailing in Swift

1. 默认的对齐方式由父控件决定

Text 默认按需占用空间,且居中对齐

struct ContentView: View {
    var body: some View {
        Text("Hello, SwiftUI!\nLorem ipsum dolor sit amet.")
            .font(.largeTitle)
            .border(.pink)
            .padding()
    }
}

如果把Text 布局在List中,则Text会靠左对齐

struct ContentView: View {
    var body: some View {
        List {
            Text("Hello, SwiftUI!\nLorem ipsum dolor sit amet.")
                .font(.largeTitle)
                .border(.pink)
                .padding()
        }
    }
}


从上可知,Text 默认的对齐方式由父控件决定

2. 使用frame辅助改变对齐方式

使用``.frame(maxWidth: .infinity)`可以制造隐形的空间占用

struct ContentView: View {
    var body: some View {
        Text("Hello, SwiftUI!\nLorem ipsum dolor sit amet.")
            .border(.pink) // 1
            .frame(maxWidth: .infinity, alignment: .trailing)
            .border(.blue) // 2
            .font(.largeTitle)
            .padding()
    }
}

最终可生成靠右对齐的效果

同理以下代码可以实现靠底部对齐

struct ContentView: View {
    var body: some View {
        Text("Hello, SwiftUI!\nLorem ipsum dolor sit amet.")
            .border(.pink)
            .frame(maxHeight: .infinity, alignment: .bottom)

            .border(.blue)
            .font(.largeTitle)
            .padding()
    }
}

对方向同时产生对齐作用

struct ContentView: View {
    var body: some View {
        Text("Hello, SwiftUI!\nLorem ipsum dolor sit amet.")
            .border(.pink)
            .frame(
                maxWidth: .infinity,
                maxHeight: .infinity,
                alignment: .topTrailing)
            .border(.blue)
            .font(.largeTitle)
            .padding()
    }
}

试试修改不同的alignment对齐方式:
topLeading top topTrailing leading center trailing bottomLeading bottom bottomTrailing

使用.multilineTextAlignment修改多行内部对齐方式

struct ContentView: View {
    var body: some View {
        Text("Hello, SwiftUI!\nLorem ipsum dolor sit amet.")
            .multilineTextAlignment(.center)
            .border(.pink)
            .frame(
                maxWidth: .infinity,
                maxHeight: .infinity,
                alignment: .topTrailing)
            .border(.blue)
            .font(.largeTitle)
            .padding()
    }
}

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1

Top ↑