SwiftUI基础之ZStack用法详解

2023-02-06  本文已影响0人  执念12o3
WeChat0d2b61bdbd651e8821934665c4294fdf.png
struct ContentView: View {
    var body: some View {
        VStack (spacing: 50){
            HStack(spacing: 10) {
                ZStackCaseItem(alignment: .top)
                ZStackCaseItem(alignment: .topLeading)
                ZStackCaseItem(alignment: .topTrailing)
            }
            HStack(spacing: 10) {
                ZStackCaseItem(alignment: .leading)
                ZStackCaseItem(alignment: .center)
                ZStackCaseItem(alignment: .trailing)
            }
            HStack(spacing: 10) {
                ZStackCaseItem(alignment: .bottom)
                ZStackCaseItem(alignment: .bottomLeading)
                ZStackCaseItem(alignment: .bottomTrailing)
            }
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct ZStackCaseItem: View {
    let alignment: Alignment
    let wh: CGFloat = 65.0
    
    var body: some View {
        VStack (spacing: 1){
            Text("\(alignment.name)")
                .frame(width: wh * 2)
                .background(Color.blue)
                .foregroundColor(.white)
            ZStack(alignment: alignment){
                Text("A")
                    .frame(width: wh, height: wh * 2)
                    .background(Color.yellow)
                
                Text("B")
                    .foregroundColor(.white)
                    .frame(width: wh * 2, height: wh)
                    .background(Color.black)
                    .opacity(0.7)
                
                Text("oldBirds")
                    .font(.system(size: 12))
                    .frame(width: wh * 0.8, height: wh * 0.3)
                    .background(Color.green)
                    .foregroundColor(.white)
            }
        }
    }
}

extension Alignment {
    var name: String {
        switch self {
        case .leading:
            return "leading"
        case .trailing:
            return "trailing"
        case .center:
            return "center"
        case .top:
            return "top"
        case .topLeading:
            return "topLeading"
        case .topTrailing:
            return "topTrailing"
        case .bottom:
            return "bottom"
        case .bottomLeading:
            return "bottomLeading"
        case .bottomTrailing:
            return "bottomTrailing"
        default:
            return "other"
        }
    }
}

如果本文对你有帮助,欢迎点赞、评论、收藏…

上一篇下一篇

猜你喜欢

热点阅读