在SwiftUI的滚动视图中添加新项目

时间:2020-05-19 21:02:16

标签: ios swiftui

每次尝试单击底部的蓝色按钮时,我都试图在滚动视图中添加一个包含按钮的新视图

Text](https://stackoverflow.com/image.jpg) [![enter image description here] 1

在这里,我用2个按钮创建滚动视图,并想在单击右侧按钮后添加更多内容

        HStack{
            ScrollView(.horizontal, content: {
                HStack{
                    PageStep()
                    PageStep()

                }
            })

            Button(action: {
                self.addNewStep = true
            }) {
                Image(systemName: "plus.square")
                    .frame(width: 75, height: 75)
                    .overlay(
                        RoundedRectangle(cornerRadius: 10)
                            .stroke(Color.blue, lineWidth: 5)
                )
            }.buttonStyle(PlainButtonStyle()).padding(.trailing, 10)
        }
        .padding(.leading, 10)
        .frame(minWidth: 0, maxWidth: UIScreen.main.bounds.width, minHeight: 80, alignment: .bottom)
        .foregroundColor(Color.blue)


struct PageStep: View {
    var stepPossition = String()

    var body: some View {

        Button(action: {
            print("Entrou")
        }){
            Rectangle()
                .fill(Color.red)
                .frame(width: 75, height: 75)
                .cornerRadius(10)
        }

    }
}

1 个答案:

答案 0 :(得分:1)

这是可行的方法。经过Xcode 11.4的测试。

struct ContentView: View {
    @State private var steps = 2 // pages counter

    var body: some View {
        HStack{
            ScrollView(.horizontal, content: {
                HStack{
                    // create available pages
                    ForEach(0..<steps, id: \.self) { i in
                        PageStep(stepPossition: "\(i)").id(i) // inject
                    }
                }
            })

            Button(action: {
                self.steps += 1 // << add next page
            }) {
                Image(systemName: "plus.square")
                    .frame(width: 75, height: 75)
                    .overlay(
                        RoundedRectangle(cornerRadius: 10)
                            .stroke(Color.blue, lineWidth: 5)
                )
            }.buttonStyle(PlainButtonStyle()).padding(.trailing, 10)
        }
        .padding(.leading, 10)
        .frame(minWidth: 0, maxWidth: UIScreen.main.bounds.width, minHeight: 80, alignment: .bottom)
        .foregroundColor(Color.blue)

    }
}

struct PageStep: View {
    var stepPossition: String

    var body: some View {

        Button(action: {
            print("Entrou")
        }){
            Rectangle()
                .fill(Color.red)
                .frame(width: 75, height: 75)
                .cornerRadius(10)
        }

    }
}