You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 05:27:11