iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 16
0
Software Development

利用Swift 4開發iOS App,Daily Work List系列 第 16

Day 16. Develop Day Page View Controller 3

  • 分享至 

  • twitterImage
  •  

轉眼鐵人賽過一半了!!!!

今天會重點處理中間UITableView的那一塊,就可以完成DayPage了
明天預期開發Edit Event Page的Storyboard


  1. 打開Main.storyboard,設定TableView,要為Dynamic Prototypes、Single Selection
    https://ithelp.ithome.com.tw/upload/images/20181016/201119161wInA7jgiV.png
  2. 接著設定Table View Cell,Indentifier和Class都為EventTableViewCell
    https://ithelp.ithome.com.tw/upload/images/20181016/20111916pBEb2chouv.png
    https://ithelp.ithome.com.tw/upload/images/20181016/20111916PL93n1jNBt.png
  3. 新增EventTableViewCell.swift,將Title Label拖拉新增Outlet、另外建立一個id變數要儲存tb_event.id欄位值用
    https://ithelp.ithome.com.tw/upload/images/20181016/20111916KbMNjemyiQ.png
  4. 建立Event.swift 的Struct 於Model Group下
    https://ithelp.ithome.com.tw/upload/images/20181016/20111916ZYlWs8CvRg.png

這樣開始寫View Controller之前的作業就完成啦~然後說明一下,因為在開發的過程中因為遇到一些問題,還有發現更多iOS原生可以使用的元素後,我調整了一下UITableViewCell裡面的元件,把Button刪掉,只留下UILabel來顯示Event,是否已完成我將改用accessoryType呈現

接下來就來完成程式的部分

開啟DayViewController.swift,我們先加入兩個TableView的Protocol

class DayViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextViewDelegate {

然後新增三個變數

// event array儲存event資料
var eventList: [Event] = [Event]()
// cell的identifier
let cellIdentifier: String = “EventTableViewCell"
// 建立一個Refresh Control,下拉更新資料使用
var refreshControl: UIRefreshControl!

在viewDidLoad()加入設定

// 設置委任對象
eventTableView.delegate = self
eventTableView.dataSource = self
// 註冊 cell(但有使用Storyboard的情況下不需再次註冊,已有設定)
// eventTableView.register(EventTableViewCell.self, forCellReuseIdentifier: cellIdentifier)
// Refresh Control
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(reloadEventTableView), for: UIControlEvents.valueChanged)
eventTableView.addSubview(refreshControl)

接著加入協定的功能

// get the count of elements you are going to display in your tableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.eventList.count
}

// assign the values in your array variable to a cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // 建立Cell以Event Table View Cell的型別
    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! EventTableViewCell
    // 設定Title內容
    cell.titleLabel.text = self.eventList[indexPath.row].name
    // 將以event的id記錄到cell中
    cell.id = self.eventList[indexPath.row].id
    // 如果這個event是完成的,就打勾顯示,否則不顯示
    if self.eventList[indexPath.row].finish {
        cell.accessoryType = .checkmark
    } else {
        cell.accessoryType = .none
    }
    return cell
}

// register when user taps a cell
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! EventTableViewCell
    // 如果這個event是完成的,就要取消打勾,否則打勾,同時異動資料庫
    if self.eventList[indexPath.row].finish {
        self.eventList[indexPath.row].finish = false
        cell.accessoryType = .none
        sqlManager.updateEventFinishById(id: cell.id, finish: false)
    } else {
        self.eventList[indexPath.row].finish = true
        cell.accessoryType = .checkmark
        sqlManager.updateEventFinishById(id: cell.id, finish: true)
    }
}

// 設定table view cell可以Swipe顯示按鈕
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? {
    // Delete 功能按鈕
    let delete = UITableViewRowAction(style: .normal, title: "Delete") { action, indexPath in
        // 刪除資料庫內容
        self.sqlManager.deleteEventById(id: self.eventList[indexPath.row].id)
        // 移除array中的該筆資料
        self.eventList.remove(at: indexPath.row)
        // 將畫面上的cell移除
        tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade)
    }
    delete.backgroundColor = UIColor.red
    
    // Edit 功能按鈕
    let edit = UITableViewRowAction(style: .normal, title: "Edit") { action, indexPath in
        print("favorite button tapped")
    }
    edit.backgroundColor = UIColor.lightGray
    
    return [edit, delete]
}

接著,把reload的功能加入,記得changeDate()的時候也要呼叫噢!

@objc func reloadEventTableView() {
    // 移除array中的所有資料
    eventList.removeAll()
    // 加入新查詢回來的資料
    eventList.append(contentsOf: sqlManager.queryEventByDate(date: dateFormatter.string(from: datePicker.date)))
    // reload table view
    self.eventTableView.reloadData()
    // 結束refresh control
    self.refreshControl.endRefreshing()
}

最後,把SQLiteManager.swift加上要用到的功能

func queryEventByDate(date: String) -> Array<Event> {
    var eventList:[Event] = [Event]()
    do {
        for result in Array(try database.prepare(TB_EVENT.filter(TB_EVENT_DAY == date))) {
            eventList.append(Event(id: result[TB_EVENT_ID], day: result[TB_EVENT_DAY], name: result[TB_EVENT_NAME], time: result[TB_EVENT_TIME], category: result[TB_EVENT_CATEGORY], reminder: result[TB_EVENT_REMINDER], place: result[TB_EVENT_PLACE], lat: result[TB_EVENT_LAT], lng: result[TB_EVENT_LNG], note: result[TB_EVENT_NOTE], finish: result[TB_EVENT_FINISH]))
        }
    } catch {
    }
    return eventList
}
func updateEventFinishById(id: Int64, finish: Bool) {
    do {
        let item = TB_EVENT.filter(TB_EVENT_ID == id)
        if try database.run(item.update(TB_EVENT_FINISH <- finish)) > 0 {
            print("update event")
        }
    } catch {
    }
}
func deleteEventById(id: Int64) {
    let item = TB_EVENT.filter(TB_EVENT_ID == id)
    do {
        if try database.run(item.delete()) > 0 {
            print("deleted event")
        }
    } catch {
        print("delete failed: \(error)")
    }
}

這樣就完成了喔!

https://ithelp.ithome.com.tw/upload/images/20181016/20111916rB91UjY4ip.png https://ithelp.ithome.com.tw/upload/images/20181016/20111916tFddu8Hfoy.png

上一篇
Day 15. Develop Day Page View Controller 2
下一篇
Day 17. Develop Edit Event Page Storyboard
系列文
利用Swift 4開發iOS App,Daily Work List31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言