Frame in SwiftUI

222 阅读1分钟

这一节的东西很少,但是很重要。因为frame无处不在,理解和应用好,会创造出很多好看的UI。
以下是示例代码和效果

image.png

struct FrameSample: View {
    var body: some View {
        Text("Hello, World!")
            .background(Color.red)
            .frame(width: 200, height: 100)
            .background(Color.orange)
            .frame(maxWidth: .infinity)
            .background(Color.blue)
            .frame(maxHeight: 400)
            .background(Color.brown)
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.purple)
    }
}

以上就是一个以 Text 为例子的,多个 frame 的例子。

frame 方法的定义是这样的,有多个可选参数。你可以使用 alignment 来设置对其方式

@inlinable public func frame(
minWidth: CGFloat? = nil, 
idealWidth: CGFloat? = nil, 
maxWidth: CGFloat? = nil,
minHeight: CGFloat? = nil, 
idealHeight: CGFloat? = nil,
maxHeight: CGFloat? = nil, 
alignment: Alignment = .center
) -> some View

例如稍加改动,就可以改变布局的形式

image.png

struct FrameSample: View {
    var body: some View {
            Text("Hello, World!")
                .background(Color.red)
                .frame(width: 200, height: 100, alignment: .center)
                .background(Color.orange)
                .frame(maxWidth: .infinity)
                .background(Color.blue)
                .frame(maxHeight: 400, alignment: .top)
                .background(Color.brown)
                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
                .background(Color.purple)
    }
}

所以用frame布局是很灵活的,虽然这个知识点很简单,但是很重要!!!!