SwiftUI基础之VStack用法详解

WeChat8d05b1bf43bddf304bac80af6e51387c.png
struct ContentView: View {
    var body: some View {
        VStack (spacing: 20){
            VStackCaseItem(alignment: .leading)//子视图局左对齐
            VStackCaseItem(alignment: .trailing)//子视图局右对齐
            VStackCaseItem(alignment: .center)//子视图局中对齐
        }
        ///使 VStack 填充屏幕的宽度
        //方案一:设置 frame
//        VStack (alignment: .leading) {
//            Text("标题")
//                .font(.title)
//                .background(Color.yellow)
//            Text("内容")
//                .lineLimit(nil)
//                .font(.body)
//                .background(Color.blue)
//        }
//        .frame(
//            maxWidth: .infinity,
//            maxHeight: .infinity,
//            alignment: .topLeading
//        )
//        .background(Color.red)
        
        //方案二:结合 HStack 和 Spacer
//        HStack {
//            VStack(alignment: .leading) {
//                Text("标题")
//                    .font(.title)
//                    .background(Color.yellow)
//                Text("内容")
//                    .lineLimit(nil)
//                    .font(.body)
//                    .background(Color.blue)
//                Spacer()
//            }
//            Spacer()
//        }.background(Color.red)
    }
}

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

struct VStackCaseItem: View {
    let alignment: HorizontalAlignment
    
    var body: some View {
        VStack(alignment: alignment, spacing: 20) {
            Text("A\nB")
                .frame(width: 50)
                .background(Color.yellow)
            
            Text(alignment.name)
                .foregroundColor(.white)
                .frame(width: 150)
                .background(Color.red)
            
            Text("oldBirds")
                .background(Color.green)
                .foregroundColor(.white)
        }.background(Color.gray)
    }
}
extension HorizontalAlignment {
    var name: String {
        switch self {
        case .leading:
            return "leading"
        case .trailing:
            return "trailing"
        case .center:
            return "center"
        default:
            return "other"
        }
    }
}

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容