iT邦幫忙

2025 iThome 鐵人賽

DAY 19
0
生成式 AI

Swift一下就會了系列 第 19

Day 19 留言板 4

  • 分享至 

  • xImage
  •  

昨天我們把TableView的架構給建立完成了,我們今天再來把它完善。

TableView 設定

首先,我們需要設定 TableView,讓它能夠正確顯示留言內容。

// tableView 設定
    func tableSet() {
        
        // 註冊cell
        tbvData?.register(UINib(nibName: "MainTableViewCell", bundle: nil), forCellReuseIdentifier: "MainTableViewCell")
        
        // 設置代理
        tbvData.dataSource = self
        tbvData.delegate = self
    }
  • register:註冊我們自訂的 MainTableViewCell,並告訴 TableView 之後要用這個樣式顯示每一列資料。
  • dataSource與delegate:設定資料來源與操作的委派,負責顯示資料與處理滑動、點擊等事件。

取得系統時間

每筆留言都需要紀錄時間,因此我們建立一個函式,取得當前的系統時間

// 設置時間
    func getSystemTime() -> String {
        let currentDate = Date()
        let dateFormatter: DateFormatter = DateFormatter()
        
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dateFormatter.locale = Locale.ReferenceType.system
        dateFormatter.timeZone = TimeZone.ReferenceType.system
        return dateFormatter.string(from: currentDate)
    }

當使用者發送或編輯留言時,就能呼叫這個函式,把時間一起存到資料庫。

排序留言

為了讓最新或最舊的留言能依需求排序,我們建立sortMessages函式。

    // 排序
    func sortMessages() {
        
        messageArray.sort { (messages1, messages2) -> Bool in
            
            if isAscending {
                return messages1.currentTime < messages2.currentTime // 由舊到新
            } else {
                return messages1.currentTime > messages2.currentTime // 由新到舊
            }
        }
    }

透過 isAscending,我們可以控制時間的排序方式升冪或降冪

從資料庫讀取留言

接著是將 Realm 中儲存的資料讀取出來並顯示在 TableView

    func dataBase() {
        let realm = try! Realm() // 連接資料庫
        let messageBoards = realm.objects(MessageBoard.self) // 讀取 MessageBoard 物件
        messageArray = Array(messageBoards) // 轉換成陣列
        sortMessages() // 排序
        tbvData.reloadData() // 重新載入 TableView
        print("file :a \(realm.configuration.fileURL!)") // 顯示資料庫位置
}

抓出資料庫中所有 MessageBoard 的資料,並存入messageArray陣列供 TableView 使用。

顯示提示視窗

為了在需要時提醒使用者,我們做一個通用的訊息彈窗。

    // 顯示警告視窗
    func showAlert(message: String) {
        let alert = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "確定", style: .default, handler: nil))
        present(alert, animated: true, completion: nil)
    }

這個小工具可以在任何情況下呼叫,顯示一個簡單的提醒訊息。

結語

今天我們完成了留言板的資料操作功能讀取並排序留言

明天我們可以來做左滑刪除留言右滑編輯留言的功能了。


上一篇
Day 18 留言板 3
下一篇
Day 20 留言板 5
系列文
Swift一下就會了20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言