- 实现思路:
- 首先定义一个变量来表示用户权限状态。
- 创建一个视图,在视图中添加按钮。
- 为按钮添加点击事件处理,根据用户权限状态显示不同选项的
ActionSheet
。
- 关键代码片段:
import SwiftUI
struct ContentView: View {
// 表示用户权限状态,假设0为普通user,1为admin
@State private var userRole = 0
@State private var isPresentingActionSheet = false
var body: some View {
VStack {
Button("点击弹出ActionSheet") {
isPresentingActionSheet = true
}
}
.actionSheet(isPresented: $isPresentingActionSheet) {
if userRole == 0 {
return ActionSheet(title: Text("普通用户选项"), message: Text("以下是普通用户可操作项"), buttons: [
.default(Text("普通操作1")),
.default(Text("普通操作2")),
.cancel()
])
} else {
return ActionSheet(title: Text("管理员选项"), message: Text("以下是管理员可操作项"), buttons: [
.default(Text("管理操作1")),
.default(Text("管理操作2")),
.destructive(Text("危险操作")),
.cancel()
])
}
}
}
}
- 解释:
@State
修饰的userRole
变量用于存储用户权限状态,isPresentingActionSheet
用于控制ActionSheet
的显示。
Button
的点击事件将isPresentingActionSheet
设置为true
,从而触发actionSheet
的显示。
- 在
actionSheet
的闭包中,根据userRole
的值创建不同选项的ActionSheet
。普通用户的ActionSheet
只有普通操作选项和取消按钮,管理员的ActionSheet
有管理操作选项、危险操作选项和取消按钮。