提问者:小点点

如何在文本视图中对文本进行混洗?


嘿,我是一个Swift的初学者,我用文本创建了一个文本视图,现在我想要当我点击按钮时,文本会洗牌。 首先,我使用了shuffle(),但它只能对数组中的文本进行shuffle。 问题是每次的文本都可能不同。 所以我不能做一个固定的数组。 我也试过做一个空数组,设置在文本上,但是失败了。 如何在文本视图中对文本进行洗牌?


共1个答案

匿名用户

当然不是最优雅的版本,但它可以做到你想做的事情:(在iOS 13.5上测试)

struct ContentView: View {
    
    @State var text = "There will be text"

    
    var body: some View {
        VStack() {
            
            Text(self.text)
            
            Button(action: {
                // new empty array. Could also be outside
                var arr: Array<String> = []

                //Split current text at every space
                for s in self.text.split(separator: " ") { 
                    arr.append(String(s)) //append to new array

                    // if length of new array is the length of all substrings
                    if arr.count == self.text.split(separator: " ").count {
                        arr.shuffle()
                        self.text = "" // empty Text field
                        for s in arr {
                            self.text.append(s + " ")
                        }
                    }
                }
            }){
                Text("Button")
            }
        }
    }
    
}