保存文件时使用第一行内容作为文件名

This commit is contained in:
2026-07-12 21:10:34 +08:00
parent 0c202ac284
commit 76c3509118
+45
View File
@@ -12,6 +12,7 @@ class FormatLogViewController: UIViewController {
private var textView: UITextView!
private var formatButton: UIButton!
private var doneButton: UIBarButtonItem!
private var isFormatted = false
override func viewDidLoad() {
super.viewDidLoad()
@@ -61,7 +62,40 @@ class FormatLogViewController: UIViewController {
}
@objc private func didTapFormatButton() {
if isFormatted {
saveToFiles()
} else {
textView.text = formatLog(textView.text)
isFormatted = true
formatButton.setTitle("保存到 iCloud", for: .normal)
}
}
private func saveToFiles() {
let fileName = generateFileName()
let fileURL = FileManager.default.temporaryDirectory.appendingPathComponent(fileName)
do {
try textView.text.write(to: fileURL, atomically: true, encoding: .utf8)
let documentPicker = UIDocumentPickerViewController(forExporting: [fileURL], asCopy: true)
documentPicker.delegate = self
present(documentPicker, animated: true)
} catch {
print("Failed to write file: \(error)")
}
}
private func generateFileName() -> String {
let text = textView.text ?? ""
let firstLine = text.components(separatedBy: .newlines).first ?? ""
let trimmed = firstLine.trimmingCharacters(in: .whitespaces)
let withoutHash = trimmed.replacingOccurrences(of: "^#\\s*", with: "", options: .regularExpression)
let cleanName = withoutHash.trimmingCharacters(in: .whitespaces)
if cleanName.isEmpty {
return "formatted_log_\(Int(Date().timeIntervalSince1970)).md"
}
return cleanName + ".md"
}
private func formatLog(_ text: String) -> String {
@@ -97,3 +131,14 @@ extension FormatLogViewController: UITextViewDelegate {
navigationItem.rightBarButtonItem = nil
}
}
extension FormatLogViewController: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
// File saved to selected location
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
// User cancelled
}
}