今天我們把tableView做更新
func updateData(){
users = []
let allorders = realm.objects(Users.self)
guard allorders.count > 0 else { print("nil");return }
for i in 1...allorders.count{
users.append(structData(setUser: allorders[i-1].name, setPassword: String(allorders[i-1].password), setEmail : allorders[i-1].email, setId : allorders[i-1].UserID))//把每個資料寫進剛剛宣告得空陣列
}
MyTableView?.reloadData()//更新TableView
}
刪除功能:
我們用primaryKey去做刪除我們選定的資料,之後除了要再tableView做deleteRows,realm也要寫delete把他刪除
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let userId = NSPredicate(format: "UserID = %@", self.users[indexPath.row].setId)
let deleteUser = realm.objects(Users.self).filter(userId)
let deleteAction = UIContextualAction(style:.destructive, title: "delete") { [self] (action , sourceView ,complete) in
self.users.remove(at: indexPath.row)
self.MyTableView.deleteRows(at: [indexPath], with: .top)
try! self.realm.write{
realm.delete(deleteUser)
}
complete(true)
}
最後我們可以,創建一個UserVC,然後再didSelectRowAt,把點擊使用者會跳頁的功能做出來,當然裡面你可以在客製化你想要顯示的內容,我這邊是顯示使用者名稱而已
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let switchToSecondScreen = UserVC()
switchToSecondScreen.UserVariable = users[indexPath.row].setUser
self.navigationController?.pushViewController(switchToSecondScreen, animated: true)
}
UserVC:
import UIKit
class UserVC: UIViewController {
@IBOutlet var UserNameLabel: UILabel!
var UserVariable: String!
override func viewDidLoad() {
UserNameLabel.text = UserVariable
super.viewDidLoad()
}
}
記得用一個變數去儲存我們要傳的值會比較好,可以避免掉程式不會執行的錯誤
今天實作就到這邊~