ConfirmationDialog in SwiftUI

391 阅读1分钟

本文的title是sheet,在iOS15之前我们使用actionsheet来显示需要多个button操作的alert。但是在iOS15由于API变更,它的名称也将改为confirmationDialog。 confirmationDialog和前一篇文章将的alert及其相似。所以本篇就不再过多赘述如何使用confirmationDialog,下面会给出一个根据不同枚举值弹出不同的confirmationDialog例子,下图为效果图

Screenshot 2023-07-24 at 21.28.08.png

struct AlertSheetSample: View {
    
    @State var showSheet: Bool = false
    @State var type: confirmationDialogType = .myProfile
    
    enum confirmationDialogType {
        case myProfile
        case more
    }
    
    var body: some View {
        ZStack {
            Color.blue
                .edgesIgnoringSafeArea(.all)
            
            VStack {
                HStack {
                    Button {
                        type = .myProfile
                        showSheet.toggle()
                    } label: {
                        Image(systemName: "camera.macro.circle")
                            .foregroundColor(Color.black)
                    }
                    
                    Text("SwiftUI tutorail")
                        .font(.subheadline)
                    
                    Spacer()
                    
                    Button {
                        type = .more
                        showSheet.toggle()
                    } label: {
                        Image(systemName: "ellipsis")
                            .foregroundColor(Color.black)
                    }
                }
                .padding(.horizontal)
                
                Rectangle()
                    .fill(Color.mint)
                    .frame(maxWidth: .infinity, maxHeight: 300)
            }
            .confirmationDialog("sss", isPresented: $showSheet, actions: sheetContentView, message: sheetTitleView)
        }
    }
    
    func sheetContentView() -> some View {
        VStack {
            switch type {
                case .more:
                    Button("Cut", action: {})
                    Button("Past", action: {})
                    Button(role: .destructive, action: {}) {
                        Text("Delete")
                    }
            case .myProfile:
                Button("Cut", action: {})
                Button("Past", action: {})
            }
        }
    }
    
    func sheetTitleView() -> some View {
        VStack {
            switch type {
            case .more:
                Text("More operations")
            case .myProfile:
                Text("This is Myprofile")
            }
        }
    }
}

上述代码是根据不同的枚举值弹出不同的confirmationDialog,当你点击左边头像时会弹出带有Cut和Past字样的confirmationDialog. 当你点击右边更多时,会左边视图的基础上多了一个删除操作按钮。

需要注意的时,根据每个不同的版本,sheetContentView和sheetTitleView方法的写法都会有所不同,本次的教程中,如果外出不包一个VStack之内的容器就会报错。我也找寻了其他的例子,有很多都没有包一层VStack,但是也是可以正常工作的。所以对于不同版本的变更,如果遇到错误,还需结合之前的知识来处理错误问题。

大家有什么看法呢?欢迎留言讨论。 公众号:RobotPBQ