下面是前篇文章 ViewController的程式碼,我將用註解大概解釋流程以及狀況
關於@obj的解釋以及參考:
簡單來說就是 swift的程式碼給 Object C 來使用,所以swift相關語言的特性就變成 Object C的特性
//
// ViewController.swift
// MyToDoList
//
// Created by Afraz Siddiqui on 4/28/20.
// Copyright © 2020 ASN GROUP LLC. All rights reserved.
//
import RealmSwift
import UIKit
/*
- To show list of current to do list itmes
- To enter new to do list items
- To show previously entered to do list item
- Item
- Date
*/
//@objc 代表可能要用到 objective C的消息調用機制來
class ToDoListItem: Object {
@objc dynamic var item: String = ""
@objc dynamic var date: Date = Date()
}
//Declare that the class implements the table view datasource and delegate protocols.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var table: UITableView!
private let realm = try! Realm()//算是宣告realm這個常數實體
private var data = [ToDoListItem]()//宣告ToDoListItem這個object的陣列或串列
override func viewDidLoad() {
super.viewDidLoad()
data = realm.objects(ToDoListItem.self).map({ $0 })//將資料裝入
table.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
//tableview的綁定或註冊
table.delegate = self
table.dataSource = self
//連結資料來源以及 Table的委派指到 ViewController上,
}
// Mark: Table
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
// 表格的儲存格設定
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = data[indexPath.row].item
return cell
}
//delete
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
// Open the screen where we can see item info and delete
let item = data[indexPath.row]
guard let vc = storyboard?.instantiateViewController(identifier: "view") as? ViewViewController else {
return
}
vc.item = item
vc.deletionHandler = { [weak self] in
self?.refresh()
}
vc.navigationItem.largeTitleDisplayMode = .never
vc.title = item.item
navigationController?.pushViewController(vc, animated: true)
}
//add
@IBAction func didTapAddButton() {
guard let vc = storyboard?.instantiateViewController(identifier: "enter") as? EntryViewController else {
return
}
vc.completionHandler = { [weak self] in
self?.refresh()
}
vc.title = "New Item"
vc.navigationItem.largeTitleDisplayMode = .never
navigationController?.pushViewController(vc, animated: true)
}
func refresh() {
data = realm.objects(ToDoListItem.self).map({ $0 })
table.reloadData()
}
}
夢想還是要有的,萬一實現不了呢? ....那起碼你到死之前都還有夢想