我不知道如何從我的視圖模型視圖中的數據傳遞給我的看法,最後顯示的數據,我的視圖模型類:如何從視圖模型層將數據傳遞給視圖層
class MainViewModel {
let sessionController: SessionController
weak var mainViewCoordinator: MainViewCoordinator?
public var fakeUsers: [User]?
init(sessionController: SessionController = SessionController()) {
self.sessionController = sessionController
}
func viewDidLoad() {
Service.instance.execute(resource: User.fake) { (result) in
print("\n result \(result)\n")
self.fakeUsers = result.value
}
}
}
我使用的Unbox夫特JSON解碼器,以及打印結果是是和用戶的對象數組是這樣的:
([
User(id: "5851ac2615801e2348e4ea07",
birthDate: "2016-09-17T07:22:09.985Z",
msisdn: "912 065 979",
email: "[email protected]",
profileImageUrl: "https://s3.amazonaws.com/...",
repPoints: 41607,
created: "2016-12-14T20:31:34.185Z",
displayName: "Victoria Escobedo"),
User(id: "5851ac2615801e2348e4ea09",
birthDate: "2016-05-06T11:38:23.678Z",
msisdn: "958842030",
email: "[email protected]",
profileImageUrl: "https://s3.amazonaws.com/...",
repPoints: 71408,
created: "2016-12-14T20:31:34.198Z",
displayName: "Gonzalo Rascón"),
User(id: "5851ac2615801e2348e4ea08",
birthDate: "2016-05-29T18:12:32.423Z",
msisdn: "905534639",
email: "[email protected]",
profileImageUrl: "https://s3.amazonaws.com/...",
repPoints: 24164,
created: "2016-12-14T20:31:34.195Z",
displayName: "Ramiro Dueñas"),
...
])
我想的結果傳遞給查看層(MainViewController)來顯示每個用戶在表視單元格中:
類MainViewController:UIViewController中,UITableViewDataSource {
@IBOutlet var tableview:UITableView!
var viewModel: MainViewModel = MainViewModel()
override func viewDidLoad() {
super.viewDidLoad()
viewModel.viewDidLoad()
self.tableview?.reloadData()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Action", style: .plain, target: self, action: #selector(action))
}
func action() {
viewModel.userDidSelectItem(identifier: "xxxx")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.fakeUsers?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "fakeUserObjectCell") as! MainTableViewCell
cell.fakeUserObject = viewModel.fakeUsers?[(indexPath as NSIndexPath).row]
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "detailSegue" {
let detailMainViewController = segue.destination as! DetailMainViewController
if let indexPath = tableview.indexPath(for: sender as! MainTableViewCell) {
detailMainViewController.id = viewModel.fakeUsers?[(indexPath as NSIndexPath).row].id
}
}
}
}
我知道我必須實現self.tableview?.reloadData()
展現fakeusers,但我不知道如何來傳遞數據,最後證明這一點。
我剛纔編輯的代碼,但我忘了什麼東西,因爲這個問題仍然存在 – Edu
@Edu是的,我們錯過了在第一流的組件,檢查編輯。 – ystack