如何在文本视图中随机播放文本?
How can I shuffle text in a Text View?
嘿,我是 Swift 的初学者,我创建了一个带有文本的文本视图,现在我希望当我单击按钮时文本随机播放。首先我使用 shuffle() 但它只能随机排列数组中的文本。问题是文本每次都可能不同。所以我不能做一个固定的数组。我还尝试制作一个空数组并将其设置在文本上,但失败了。如何在文本视图中随机排列文本?
当然不是最优雅的版本,但它可以做你想做的事:
(在 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")
}
}
}
}
嘿,我是 Swift 的初学者,我创建了一个带有文本的文本视图,现在我希望当我单击按钮时文本随机播放。首先我使用 shuffle() 但它只能随机排列数组中的文本。问题是文本每次都可能不同。所以我不能做一个固定的数组。我还尝试制作一个空数组并将其设置在文本上,但失败了。如何在文本视图中随机排列文本?
当然不是最优雅的版本,但它可以做你想做的事: (在 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")
}
}
}
}