SwiftUI Picker中实现通知铃声预览按钮,选中后隐藏按钮
实现SwiftUI Picker选中项隐藏预览按钮
你只需要给每个预览按钮加个显示条件:当选项未被选中时才显示按钮,通过对比当前选中的toneSelection和选项的tag就能实现。
修改后的代码如下:
struct SettingsView: View { // 假设你已定义NotificationType枚举和toneSelection绑定变量 enum NotificationType { case simple, reverb } @State private var toneSelection: NotificationType = .simple // 你的playPreview方法 func playPreview(previewSound: String) { // 这里写播放铃声的逻辑 } var body: some View { NavigationStack { Form { Toggle("Push Notifications", isOn: .constant(true)) Picker("Tone", selection: $toneSelection) { HStack { Text("Simple") // 未选中当前项时显示预览按钮 if toneSelection != .simple { Button(action: {playPreview(previewSound: "Sound1")}) { Image(systemName: "speaker.wave.3.fill") } } }.tag(NotificationType.simple) HStack { Text("Reverb") // 未选中当前项时显示预览按钮 if toneSelection != .reverb { Button(action: {playPreview(previewSound: "Sound2")}) { Image(systemName: "speaker.wave.3.fill") } } }.tag(NotificationType.reverb) } .pickerStyle(.navigationLink) } } } }
逻辑说明
- 每个选项的预览按钮通过
if toneSelection != 对应tag判断显示状态 - 用户选中某选项后,该选项的预览按钮自动隐藏,未选中的选项仍保留预览功能
- 完全复用你原有的Picker结构,不需要调整Picker样式或导航逻辑
内容的提问来源于stack exchange,提问作者Zack A
相关产品推荐
相关产品推荐

