-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOld.swift
520 lines (397 loc) · 19.7 KB
/
Old.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//
// ViewController.swift
// Money Tracker
//
// Created by Zeeshan Waheed on 29/03/2024.
//
import UIKit
import Foundation
class MoneyTrackerVC: UIViewController {
// table view variable
@IBOutlet var tableView: UITableView!
// class used to store data about cells
var transactionList = [cellData]()
// current balance variable
@IBOutlet var labelCurrentBalance: UILabel!
// variable to store the current balance number
var currentbalanceNumber = 0
// UITableView Backgroung Image
@IBOutlet var imageStackViewBG: UIImageView!
// money spent or recieved buttons background Image
@IBOutlet var imageMoneyAddAndSpentBG: UIImageView!
// category
var selectedCategoryForMoneySpent: String?
// category
var selectedCategoryForMoneyAdded: String?
// setting array for spent money category and add money category
let categoriesSpentMoney = ["Food", "Groceries", "Travelling", "Vehicle", "Education", "Household", "Socialising", "Clothes", "Mobile", "Other"]
let categoriesAddMoney = ["Allowance", "Salary", "Petty cash", "Bonus", "Other"]
override func viewDidLoad() {
super.viewDidLoad()
print("Documents folder is \(documentsDirectory())")
print("Data file path is \(dataFilePath())")
// to keep the app appearance light mode
overrideUserInterfaceStyle = .light
// loading previous state using data persistence
// loadChecklistItems()
// function that contains all the configuration
configureMoneyTrackerVC()
}
func documentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
func dataFilePath() -> URL {
return documentsDirectory().appendingPathComponent("Checklists.plist")
}
//
// func saveChecklistItems() {
// let encoder = PropertyListEncoder()
// do {
// let data = try encoder.encode(transactionList)
// try data.write(to: dataFilePath(), options: Data.WritingOptions.atomic)
// } catch {
// print("Error encoding item array: \(error.localizedDescription)")
// }
// }
//
//
//
// func loadChecklistItems() {
// let path = dataFilePath()
//
// if let data = try? Data(contentsOf: path) {
// let decoder = PropertyListDecoder()
// do {
// transactionList = try decoder.decode([cellData].self, from: data)
// } catch {
// print("Error decoding item array: \(error.localizedDescription)")
// }
// }
// }
//
// a function containing all element code
func configureMoneyTrackerVC() {
// to keep the app appearance light mode
overrideUserInterfaceStyle = .light
tableView.delegate = self
tableView.dataSource = self
// applying border radius function
applyBorderRadius()
// initially current balance label displays 0
labelCurrentBalance.text = "\(currentbalanceNumber) Rs"
// setting background image for the UITableView
let backgroundImage = UIImage(named: "Transaction History BG")
let imageView = UIImageView(image: backgroundImage)
imageView.contentMode = .scaleAspectFill
self.tableView.backgroundView = imageView
tableView.layer.cornerRadius = 46
}
func allSum() {
var num = 0
}
// border radius function for the money spent or money added button background image
func applyBorderRadius() {
imageStackViewBG.layer.cornerRadius = 55
imageMoneyAddAndSpentBG.layer.cornerRadius = 30
labelCurrentBalance?.layer.cornerRadius = 8
labelCurrentBalance?.layer.masksToBounds = true
}
// function to get currten date
func getCurrentDate() -> String {
// Get the current date
let currentDate = Date()
// Create a calendar object
let calendar = Calendar.current
// Get the components of the current date
let components = calendar.dateComponents([.year, .month, .day], from: currentDate)
// Extract the day, month, and year from the components
let day = components.day
let month = components.month
let year = components.year
// Return the current date as a formatted string
return "\(day!)-\(month!)-\(year!)"
}
// adding the transaction data to the transactionList
func addTransaction(_ transaction: cellData) {
transactionList.insert(transaction, at: 0)
}
// function to add categories drop down menu
func categories(ac: UIAlertController, categoryType categories: [String], isEditButton: Bool) {
var placeHolderText = "Category"
if isEditButton == true {
if categories.count > 5{
placeHolderText = "\(self.selectedCategoryForMoneySpent ?? "Other")"
} else {
placeHolderText = "\(self.selectedCategoryForMoneyAdded ?? "Other")"
}
}
ac.addTextField(configurationHandler: { textField in
textField.placeholder = "\(placeHolderText)"
let button = UIButton(type: .custom)
button.setTitle("Select", for: .normal)
// Create a menu with categories
let categoriesMenu = UIMenu(title: "Categories", children: categories.map { category in
UIAction(title: category) { action in
if categories.count > 5 {
self.selectedCategoryForMoneySpent = category
textField.text = category
} else {
self.selectedCategoryForMoneyAdded = category
textField.text = category
}
}
})
button.menu = categoriesMenu
button.showsMenuAsPrimaryAction = true
textField.rightView = UIImageView(image: UIImage(systemName: "chevron.down"))
textField.rightView?.tintColor = .black
textField.rightViewMode = .always
textField.isUserInteractionEnabled = false
textField.superview?.addSubview(button)
ac.view.layoutIfNeeded()
button.frame = textField.superview?.bounds ?? .zero
})
}
// alert view implementation
func buttonTapped(message: String, title: String, buttonName: String) {
// setting default category as other
selectedCategoryForMoneyAdded = "Other"
selectedCategoryForMoneySpent = "Other"
let ac = UIAlertController(title: nil, message: "\(message)", preferredStyle: .alert)
// adding a text field
ac.addTextField { (textField) in
textField.placeholder = "Enter Amount"
textField.keyboardType = .numberPad // getting the num pad up
}
// showing categories depending on the tyoe of button clicked
if buttonName == "addMoney" {
categories(ac: ac, categoryType: categoriesAddMoney, isEditButton: false)
} else {
categories(ac: ac, categoryType: categoriesSpentMoney, isEditButton: false)
}
// adding submit button functionality
let SubmitAction = UIAlertAction(title: "\(title)",
style: .default) { [unowned self, ac] action in
// This is the text entry after enter key
let AddedItem = ac.textFields![0]
// using a function to add items to the uitable view and append data to transaction list and to
// sned data to currentBalance label
addMoneyOrSpentMoneyImplementation(AddedItem.text!, buttonName: buttonName)
}
// condition for Add and Spent button color
if title == "Add" {
SubmitAction.setValue(UIColor(hex: "#008000"), forKey: "titleTextColor")
} else {
SubmitAction.setValue(UIColor(hex: "#FF474D"), forKey: "titleTextColor")
}
// creating a cancel button
let cancelButton = UIAlertAction(title: "Cancel",
style: .default)
// setting cancel button color
cancelButton.setValue(UIColor(hex: "#FF6C71"), forKey: "titleTextColor")
// adding the button
ac.addAction(SubmitAction)
ac.addAction(cancelButton)
present(ac, animated: true)
}
func addMoneyOrSpentMoneyImplementation(_ item: String, buttonName: String) {
// Using this to Format the number and add commas
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
let numberEntered = Int(item)
// the formatted number
let numberFormatted = numberFormatter.string(from: NSNumber(value: numberEntered ?? 0))
// if the number entered is 0 or nothing it returns without appending it to transactionlist
if numberEntered == 0 || numberEntered == nil {
return
}
// current date store in this variable
let currentDate = getCurrentDate()
// let lastIndex = transactionList.count
var transOne: cellData
// add the cell data and displaying it according to the button name given
if buttonName == "addMoney" {
transOne = cellData(amount: "+ \(numberFormatted!) Rs", date: "\(currentDate)", moneySpentOrRecievedImage: "money-recieve", moneySpentOrRecievedBGImage: "Green Gradient", imageCategoryIcon: "\(selectedCategoryForMoneyAdded ?? "Other")")
currentbalanceNumber += numberEntered ?? 0
let currentBalanceFormattedNumber = numberFormatter.string(from: NSNumber(value: currentbalanceNumber))
labelCurrentBalance.text = "\(currentBalanceFormattedNumber!) Rs"
} else {
transOne = cellData(amount: "- \(numberFormatted!) Rs", date: "\(currentDate)", moneySpentOrRecievedImage: "money-send", moneySpentOrRecievedBGImage: "Red Gradient", imageCategoryIcon: "\(selectedCategoryForMoneySpent ?? "Other")")
currentbalanceNumber -= numberEntered ?? 0
let currentBalanceFormattedNumber = numberFormatter.string(from: NSNumber(value: currentbalanceNumber))
labelCurrentBalance.text = "\(currentBalanceFormattedNumber!) Rs"
}
addTransaction(transOne)
// adding new row at top such that latest result remains on top
let indexPath = IndexPath(row: 0, section: 0)
let indexPaths = [indexPath]
tableView.insertRows(at: indexPaths, with: .automatic)
return
}
func editAlertView(_ indexPath: IndexPath) {
let ac = UIAlertController(title: nil, message: "Edit or Delete", preferredStyle: .alert)
let numberAmount = transactionList[indexPath.row].amount
let numberString = numberAmount.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()
let number = Int(numberString)
var typeOfTransaction: String?
// setting previous category in the category button
let oldCategory = transactionList[indexPath.row].imageCategoryIcon
// setting category and displaying it in placeholder
selectedCategoryForMoneyAdded = oldCategory
selectedCategoryForMoneySpent = oldCategory
ac.addTextField { (textField) in
textField.text = "\(number ?? 0)"
textField.keyboardType = .numberPad // getting the num pad up
}
typeOfTransaction = transactionList[indexPath.row].imageMoneySpentOrRecieved
if typeOfTransaction == "money-send" {
categories(ac: ac, categoryType: categoriesSpentMoney, isEditButton: true)
} else {
categories(ac: ac, categoryType: categoriesAddMoney, isEditButton: true)
}
// adding submit button functionality
let EditAction = UIAlertAction(title: "Edit",
style: .default) { [unowned self, ac] action in
// This is the text entry after enter key
let AddedItem = ac.textFields![0]
// checking the type of transaction by image name
let typeOfTransaction = transactionList[indexPath.row].imageMoneySpentOrRecieved
// checking the number entered
// let numberEntered = Int(AddedItem.text!)
// saving previous number entered
let previousAmountNumber = transactionList[indexPath.row].amount
let numberAmountSplit = previousAmountNumber.split(separator: " ")
let amountNumber = Int(numberAmountSplit[1])
// checking if the number entered is nil or zero
let numEntered = Int(AddedItem.text!)
if typeOfTransaction == "money-send" {
if numEntered != 0 || numEntered != nil {
// if the number entered is anything other than nil or zero perform operation and update the table
// view cell
// updating the current number variable
updatingRow(transactionType: typeOfTransaction, AddedItem: AddedItem, numEntered: numEntered ?? 0, indexPath: indexPath, amountNumber: amountNumber ?? 0)
}
} else {
if numEntered != 0 || numEntered != nil {
// if the number entered is anything other than nil or zero perform operation and update the table
// view cell
// updating the current number variable
updatingRow(transactionType: typeOfTransaction, AddedItem: AddedItem, numEntered: numEntered ?? 0, indexPath: indexPath, amountNumber: amountNumber ?? 0)
}
}
}
// creating a Delete button
let deleteButton = UIAlertAction(title: "Delete",
style: .default) { _ in
let AddedItem = ac.textFields![0]
let numEntered = Int(AddedItem.text!)
let typeOfTransaction = self.transactionList[indexPath.row].imageMoneySpentOrRecieved
if typeOfTransaction == "money-send" {
self.editingLabelNumber(numberEntered: numEntered ?? 0, symbol: "-")
} else {
self.editingLabelNumber(numberEntered: numEntered ?? 0, symbol: "+")
}
self.transactionList.remove(at: indexPath.row)
let indexPaths = [indexPath]
self.tableView.deleteRows(at: indexPaths, with: .automatic)
}
// setting delete button color and edit button color
deleteButton.setValue(UIColor(hex: "#FF6C71"), forKey: "titleTextColor")
EditAction.setValue(UIColor(hex: "#008000"), forKey: "titleTextColor")
// adding the button
ac.addAction(EditAction)
ac.addAction(deleteButton)
present(ac, animated: true)
// saveChecklistItems()
}
func editingLabelNumber(numberEntered: Int, symbol: String) {
if symbol == "-" {
// updating current balance label
currentbalanceNumber += numberEntered
} else {
// updating current balance label
currentbalanceNumber -= numberEntered
}
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
let currentBalanceFormattedNumber = numberFormatter.string(from: NSNumber(value: currentbalanceNumber))
labelCurrentBalance.text = "\(currentBalanceFormattedNumber ?? " ") Rs"
}
// updating row after updating the values
func updatingRow(transactionType: String, AddedItem: UITextField, numEntered: Int, indexPath: IndexPath, amountNumber: Int) {
print("This is the num - \(numEntered)")
if numEntered != 0 {
if transactionType == "money-send" {
currentbalanceNumber += amountNumber
currentbalanceNumber -= numEntered
self.transactionList[indexPath.row].amount = "- \(AddedItem.text!) Rs"
let indexPaths = [indexPath]
// setting label to updated value
labelCurrentBalance.text = "\(currentbalanceNumber) Rs"
transactionList[indexPath.row].imageCategoryIcon = selectedCategoryForMoneySpent ?? "Other"
tableView.reloadRows(at: indexPaths, with: .automatic)
} else {
currentbalanceNumber -= amountNumber
currentbalanceNumber += numEntered
self.transactionList[indexPath.row].amount = "+ \(AddedItem.text!) Rs"
let indexPaths = [indexPath]
// setting label to updated value
labelCurrentBalance.text = "\(currentbalanceNumber) Rs"
transactionList[indexPath.row].imageCategoryIcon = selectedCategoryForMoneyAdded ?? "Other"
tableView.reloadRows(at: indexPaths, with: .automatic)
}
} else {
print("num is zero")
}
}
func cellConfiguration(cell: TrackerCell, indexPath: IndexPath) -> UITableViewCell {
// setting data of cell to display
cell.labelAmountData.text = "\(transactionList[indexPath.row].amount)"
cell.labelDateData.text = "\(transactionList[indexPath.row].date)"
cell.imageTransactionStatus.image = UIImage(named: transactionList[indexPath.row].imageMoneySpentOrRecieved)
cell.imageTransactionStatusBG.image = UIImage(named: transactionList[indexPath.row].imageMoneySpentOrRecievedBG)
cell.imageTransactionCategory.image = UIImage(named: transactionList[indexPath.row].imageCategoryIcon)
// setting background color to transparent such that there remains a space between two cells
cell.layer.backgroundColor = UIColor.clear.cgColor
// setting background imgage radius of the cell such that uniformity is obtained and it looks like a cell
cell.imageTransactionStatusBG.layer.cornerRadius = 15
return cell
}
}
extension MoneyTrackerVC: UITableViewDataSource, UITableViewDelegate {
// setting number of rows in section
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return transactionList.count
}
// setting cell height through this function
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 75
}
// number of sections in UITableView
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// selecting the cell with the identifier
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TrackerCell
// saveChecklistItems()
return cellConfiguration(cell: cell, indexPath: indexPath)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// editing function when user clicks on a table view cell
editAlertView(indexPath)
}
}
extension MoneyTrackerVC {
// add money button
@IBAction func addMoney(_ sender: Any) {
// function to check which button is tapped
buttonTapped(message: "Add Money", title: "Add", buttonName: "addMoney")
}
// money spent button
@IBAction func spentMoney(_ sender: Any) {
// function to check which button is tapped
buttonTapped(message: "Money Spent", title: "Spent", buttonName: "spentMoney")
}
}