Use of ForEach, ScrollView

1. Use of ForEach

  1.1 Basic use

    1) Realize

func testForEach1() -> some View{
    // 垂直堆栈
    VStack {
        ForEach(0..<5) { index in
            //Text("Hi: \(index)")
            HStack {
                Circle()
                    .frame(width: 30, height: 30)
                Text("Index is: \(index)")
            }
        }
    }
}

    2) Effect drawing:

  1.2 Array operations

    1) Realize

/// for 循环
struct ForEachBootcamp: View {
    
    let data: [String] = ["Hi", "Hello", "Hey everyone"]
    let myString: String = "Hello"
    
    var body: some View {
        testForEach2()
    }
    // 方式二
    func testForEach2() -> some View{
        VStack{
            ForEach(data.indices, id: \.self ) { index in
                Text("\(data[index]): \(index)")
                    .font(.body)
            }
            
            ForEach(0..<100) { index in
                //Circle()
                //.frame(height: 50)
            }
        }
    }
}

    2) Effect drawing:

2. Use of ScrollView

  2.1 Vertical scrolling

    1) Realize

//垂直滚动
func testVScrollView() -> some View{
    ScrollView(.vertical, showsIndicators: false) {
        VStack{
            ForEach(0..<50) { index in
                Rectangle()
                    .fill(Color.blue)
                    .frame(height: 300)
            }
        }
    }
}

    2) Effect drawing:

  2.2 Horizontal scrolling

    1) Realize

// 水平滚动
func testHScrollView() -> some View{
    ScrollView(.horizontal, showsIndicators: false) {
        HStack{
            ForEach(0..<50) { index in
                Rectangle()
                    .fill(Color.blue)
                    .frame(width: 300, height: 300)
            }
        }
    }
}

    2) Effect drawing:

  2.3 Double scrolling

    1) Realize

// 双层 ScrollView
func doubleScrollView() -> some View{
    ScrollView(.vertical, showsIndicators: false) {
        // LazyVStack : 大数据时,采取懒加载 V 堆栈,只显示前面一部分内容
        LazyVStack{
            ForEach(0..<20) { index in
                ScrollView(.horizontal, showsIndicators: false) {
                    HStack{
                        ForEach(0..<30) { index in
                            RoundedRectangle(cornerRadius: 25)
                                .fill(Color.white)
                                .frame(width: 200, height: 150)
                                .shadow(radius: 10)
                                .padding()
                        }
                    }
                }
            }
        }
    }
}

    2) Effect drawing:

 

Guess you like

Origin blog.csdn.net/u011193452/article/details/130850046