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

SwiftUI实现客户专属随机消息仅生成一次的方案咨询

解决思路

核心是用UserDefaults持久化存储每个客户的专属消息,首次打开时生成并保存,后续直接读取已存储内容,步骤如下:

  • 以客户的uniqueCustomer作为存储键,确保每个客户的消息独立存储
  • 进入页面时先检查UserDefaults中是否有该客户的消息:
    • 有则直接使用存储的内容
    • 无则生成随机消息,同时存入UserDefaults
  • 避免每次渲染视图时重复生成随机数
修改后的完整代码
import SwiftUI

struct ListOfMessages: View {
    @State private var isDetailViewPressed = false
    
    let uniqueCustomer: String
    let topColor: Color
    let bottomColor: Color
    
    var body: some View {
        Button(action: {
            isDetailViewPressed.toggle()
        }) {
            ZStack {
                Rectangle()
                    .fill(LinearGradient(colors: [topColor, bottomColor], startPoint: .topLeading, endPoint: .bottomTrailing))
                    .cornerRadius(13)
                    .frame(height: 120)
                    .padding(10)
                    .opacity(0.8)
                
                VStack {
                    HStack {
                        Text(uniqueCustomer)
                            .font(.largeTitle)
                            .bold()
                            .foregroundColor(.yellow)
                            .padding(30)
                        Spacer()
                    }
                    
                    Image(systemName: "envelope")
                        .font(.largeTitle)
                        .foregroundColor(.yellow)
                        .padding(.leading, 260)
                        .padding(.top, -30)
                }.padding(.top, -30)
            }
        }
        .fullScreenCover(isPresented: $isDetailViewPressed) {
            DestinationView(uniqueCustomer: uniqueCustomer)
        }
    }
}

struct DestinationView: View {
    @Environment(\.presentationMode) var presentationMode
    let uniqueCustomer: String
    
    // 计算属性:获取或生成客户的专属消息
    private var customerMessage: String {
        let userDefaults = UserDefaults.standard
        let key = "CustomerMessage_\(uniqueCustomer)"
        
        // 检查是否已存储消息
        if let savedMessage = userDefaults.string(forKey: key) {
            return savedMessage
        } else {
            // 生成随机消息并存储
            let randomNum = Int.random(in: 0...2)
            let newMessage = makeRandomPhrase(randomNumber: randomNum)
            userDefaults.set(newMessage, forKey: key)
            return newMessage
        }
    }
    
    var body: some View {
        ZStack(alignment: .topLeading) {
            
            Image("space")
                .resizable()
                .ignoresSafeArea()
            
            Button(action: {
                presentationMode.wrappedValue.dismiss()
            }, label: {
                Image(systemName: "xmark")
                    .foregroundColor(.yellow)
                    .font(.largeTitle)
                    .padding(.leading, 30)
                    .padding(.top, 10)
            })

            Text(uniqueCustomer)
                .foregroundColor(.yellow)
                .font(.system(size: 40))
                .bold()
                .padding(.top, 70)
                .padding(.leading, 30)
            
            Text(customerMessage) // 使用持久化的消息
                .foregroundColor(.white)
                .font(.system(size: 30))
                .bold()
                .padding(.top, 120)
                .padding(.leading, 30)
                .frame(width: 350)
        }
    }
    
    func makeRandomPhrase(randomNumber: Int) -> String {
        let myName = "Mário"
        
        switch randomNumber {
        case 0:
            return "Hey \(myName) I'm so glad that I had seen you out. Could we go on football match this evening? \n\nRegards,\n\(uniqueCustomer)"
        case 1:
            return "Hello \(myName) how are you? I haven't seen you for a long time. We should meet somewhere in town if you are down. \n\nAll the best,\n\(uniqueCustomer)"
        case 2:
            return "Eyo \(myName) what will we do today?"
        default:
            return "Hey \(myName) I'm so glad to see you here."
        }
    }
}
关键改动说明
  • 新增customerMessage计算属性:封装消息的读取与生成逻辑,代码更清晰
  • 存储键使用"CustomerMessage_\(uniqueCustomer)",确保不同客户的消息不会互相覆盖
  • 仅在首次进入页面时生成随机数并保存消息,后续直接读取存储内容
  • UserDefaults是轻量持久化方案,适合存储这类简单字符串数据,比手动操作JSON文件更便捷

内容的提问来源于stack exchange,提问作者Mário Markovič

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 02:17:19