You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 00:52:40