// // FormatterView.swift // Note // // Created by fish on 2026/7/12. // import SwiftUI struct FormatterView: View { @State private var inputText: String = "" @State private var resultText: String? @State private var showEmptyAlert: Bool = false var body: some View { NavigationStack { VStack(spacing: 16) { TextEditor(text: $inputText) .frame(minHeight: 160) .padding(8) .background(Color(.systemGray6)) .cornerRadius(8) .overlay( RoundedRectangle(cornerRadius: 8) .stroke(Color(.systemGray4), lineWidth: 1) ) Button(action: formatAndNavigate) { Label("格式化", systemImage: "wand.and.stars") .font(.headline) .frame(maxWidth: .infinity) .padding() .background(Color.accentColor) .foregroundStyle(.white) .cornerRadius(10) } Spacer() } .padding() .navigationTitle("文案格式化") .background(Color(hex: "f2f2f7").ignoresSafeArea()) .navigationDestination(item: $resultText) { text in ResultView(formattedText: text) } .alert("提示", isPresented: $showEmptyAlert) { Button("确定", role: .cancel) {} } message: { Text("请输入需要格式化的文案") } } } private func formatAndNavigate() { if inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { showEmptyAlert = true return } resultText = format(inputText) } private func format(_ text: String) -> String { var content = text // 去 # content = content.replacingOccurrences(of: "# ", with: "") content = content.replacingOccurrences(of: "#", with: "") // 将 ; 转为句号 content = content.replacingOccurrences(of: ";", with: "。") // 将 ; 转为句号 content = content.replacingOccurrences(of: ";", with: "。") // 将 . 转为句号 content = content.replacingOccurrences(of: ".", with: "。") // 将 ( 转为 ( content = content.replacingOccurrences(of: "(", with: "(") // 将 ) 转为 ) content = content.replacingOccurrences(of: ")", with: ")") // 将 ? 转为 ? content = content.replacingOccurrences(of: "?", with: "?") // 将 , 转为 , content = content.replacingOccurrences(of: ",", with: ",") // 将 : 转为 : content = content.replacingOccurrences(of: ":", with: ":") // 将 日星期 转为 日 星期 content = content.replacingOccurrences(of: "日星期", with: "日 星期") // 在第一行插入 # content = "# " + content // 标题设置 content = content.replacingOccurrences(of: "一、生活方面", with: "## 一、生活方面") content = content.replacingOccurrences(of: "二、交易方面", with: "## 二、交易方面") content = content.replacingOccurrences(of: "三、工作方面", with: "## 三、工作方面") return content } } #Preview { FormatterView() }