SwiftUI:将绑定字符串拆分为字符串数组的实现问题
解决TextEditor内容拆分为单词存入数组的问题
你之前的错误在于stringArray2是静态计算属性,而stringArray是@State动态变量——视图初始化时stringArray为空,且静态属性无法响应stringArray的动态变化,所以这种方式行不通。另外原按钮逻辑只是把整个文本作为单个元素加入数组,没有做拆分处理。
直接在"send to the player"按钮的点击事件里对textEditorText做拆分处理即可,同时可以兼容带标点、多空格的场景,修改后的完整代码如下:
import SwiftUI struct ContentView: View { @State var textEditorText: String = "one, two, three" @State var stringArray: [String] = [] var body: some View { NavigationView { VStack{ TextEditor(text: $textEditorText) .frame(height: 200) .cornerRadius(10) Button(action: { textEditorText = "" }, label: { Text("clear the editor".uppercased()) .font(.headline) .padding(10) .frame(maxWidth: .infinity) .foregroundColor(.white) .background(Color.blue) .cornerRadius(10) }) Button(action: { guard !textEditorText.isEmpty else { return } // 定义拆分依据:空格、换行、所有标点符号 let separators = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters) // 拆分字符串→过滤空内容→去除每个单词的前后空白 let words = textEditorText.components(separatedBy: separators) .filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty } .map { $0.trimmingCharacters(in: .whitespaces) } // 替换数组内容(如果需要追加元素,改用 stringArray.append(contentsOf: words)) stringArray = words }, label: { Text("send to the player".uppercased()) .font(.headline) .padding(10) .frame(maxWidth: .infinity) .foregroundColor(.white) .background(Color.blue) .cornerRadius(10) }) Button(action: { stringArray.removeAll() }, label: { Text("clear the player".uppercased()) .padding(10) .frame(maxWidth: .infinity) .background(Color.blue.cornerRadius(10)) .foregroundColor(.white) .font(.headline) .shadow(radius: 5) }) ForEach(stringArray, id: \.self) { data in Text(data) } .frame(maxWidth:.infinity, maxHeight: 30) Spacer() } .padding(10) .background(Color.gray.opacity(0.25)) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
关键逻辑说明
CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters):覆盖所有可能的分隔场景,包括空格、换行、逗号、句号等标点filter和map组合:避免拆分后出现空字符串,同时确保每个单词前后没有多余空格- 直接赋值
stringArray = words:一次性替换数组内容,符合你原逻辑中"清空后添加"的需求(如果需要追加历史内容,可改为stringArray.append(contentsOf: words))
内容的提问来源于stack exchange,提问作者Peter_22
相关产品推荐
相关产品推荐

