ios 将 随机 TextField 显示 为 文本

kwvwclae  于 2022-11-19  发布在  iOS
关注(0)|答案(1)|浏览(145)

我想使按钮,按下将显示我们随机文本字段(从3个文本字段:username,username 2或username 3)。目前我有这样的东西,但不知道如何使它成为可能。

struct Test: View {

/// @State private var names : ??? - I don't know what should be there
    @State private var username: String = ""
    @State var username2: String = ""
    @State var username3: String = ""
    var body: some View {
        
        
        NavigationView {
            VStack {
                TextField("Your name", text: $username)
                TextField("Your name2", text: $username2)
                TextField("Your name3", text: $username3)
                
                Button(action: randomName) {
                    Text("draw")
                            
                        }
                    
             }
                
                Text("names.text") /// it doesn't work
                .foregroundColor(.black)
                .font(.largeTitle)
                
            }
        }
    }
    
    
    private func randomName() {
        let names = ["\(username)", "\(username2)", "\(username3)"]
    }
}

我试过把所有的东西都加到第一个 @State 的私有变量名里,但是没有一个能正常工作。也许我只是用了错误的方法?或者它不应该用“让名字”来完成?我不知道,也不知道。

8mmmxcuj

8mmmxcuj1#

首先您只需要添加randomName作为State。

struct Example: View {

    @State private var username: String = ""
    @State var username2: String = ""
    @State var username3: String = ""
    @State var selectedName: String = "Initial Value"
    
    var body: some View {
        NavigationView {
            VStack {
                TextField("Your name", text: $username)
                TextField("Your name2", text: $username2)
                TextField("Your name3", text: $username3)
                
                Button(action: randomName) {
                    Text("draw")
                }
                
                Text(selectedName) 
                    .foregroundColor(.black)
                    .font(.largeTitle)
            }
                    
          }
        }
        
        private func randomName() {
            let names = ["\(username)", "\(username2)", "\(username3)"]
            
            selectedName = names[Int.random(in: 0..<names.count)]
        }
}

相关问题