【问题标题】:How can I shuffle text in a Text View?如何在文本视图中随机播放文本?
【发布时间】:2020-10-11 06:19:50
【问题描述】:

嘿,我是 Swift 的初学者,我创建了一个带有文本的文本视图,现在我希望当我单击按钮时文本会随机播放。首先,我使用 shuffle() 但它只能随机播放数组中的文本。问题是每次的文本都可能不同。所以我不能制作一个固定的数组。我还尝试制作一个空数组并将其设置在文本上,但失败了。如何在文本视图中随机播放文本?

【问题讨论】:

  • 发布您的尝试以及您遇到的问题。
  • 使用Stringcomponents(separatedBy: )来制作一个字母数组。

标签: ios arrays swift textview


【解决方案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")
            }
        }
    }
    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-10
    • 2016-10-09
    • 1970-01-01
    • 2015-04-20
    • 1970-01-01
    • 2021-01-02
    • 2013-06-02
    • 1970-01-01
    相关资源
    最近更新 更多