You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
3.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import SwiftUI
import CoreData
struct CreateCodeView: View {
@Environment(\.dismiss) private var dismiss
@EnvironmentObject var coreDataManager: CoreDataManager
//
let selectedDataType: DataType
let selectedBarcodeType: BarcodeType
let selectedQRCodeType: QRCodeType
@State private var content = ""
@State private var showingAlert = false
@State private var alertMessage = ""
//
@State private var validationResult: BarcodeValidator.ValidationResult?
//
@FocusState private var isContentFieldFocused: Bool
var body: some View {
Form {
//
CodeContentInputView(
selectedDataType: selectedDataType,
selectedBarcodeType: selectedBarcodeType,
selectedQRCodeType: selectedQRCodeType,
content: $content,
validationResult: $validationResult,
isContentFieldFocused: $isContentFieldFocused
)
}
.navigationTitle("创建\(selectedDataType.displayName)")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("创建") { createCode() }
.disabled(content.isEmpty)
}
}
.alert("提示", isPresented: $showingAlert) {
Button("确定") { }
} message: { Text(alertMessage) }
.onAppear {
//
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
isContentFieldFocused = true
}
}
.onTapGesture {
//
isContentFieldFocused = false
}
}
private func createCode() {
guard !content.isEmpty else { return }
//
if selectedDataType == .barcode {
let validation = BarcodeValidator.validateBarcode(content, type: selectedBarcodeType)
if !validation.isValid {
alertMessage = validation.errorMessage ?? "条形码格式不正确"
showingAlert = true
return
}
}
let context = coreDataManager.container.viewContext
let historyItem = HistoryItem(context: context)
historyItem.id = UUID()
historyItem.content = content
historyItem.dataType = selectedDataType.rawValue
historyItem.dataSource = DataSource.created.rawValue
historyItem.createdAt = Date()
historyItem.isFavorite = false
if selectedDataType == .barcode {
historyItem.barcodeType = selectedBarcodeType.rawValue
} else {
historyItem.qrCodeType = selectedQRCodeType.rawValue
}
coreDataManager.addHistoryItem(historyItem)
alertMessage = "\(selectedDataType.displayName)创建成功!"
showingAlert = true
//
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
dismiss() //
}
}
}
#Preview {
CreateCodeView(
selectedDataType: .barcode,
selectedBarcodeType: .ean13,
selectedQRCodeType: .text
)
}