ios - Swift 分离 UITableViewDataSource

标签 ios swift uitableview model-view-controller

我的项目中有 4 个文件:

  • myTableViewController.swift
  • myTableViewDataSource.swift
  • myCustomCell.swift
  • 我的自定义单元格.xib

这是我实现的:

myTableViewController.swift:

import UIKit

class myTableViewController: UIViewController {

    let cellIdentifier: String = "myCell"// set same id in storyboard as well

    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func setup(){

        let myDataSource = myTableViewDataSource.init(str: "init!")
        tableView.registerNib(UINib(nibName: "myCustomCell", bundle: nil), forCellReuseIdentifier: "myCell")
        tableView.dataSource = myDataSource
    }

myTableViewDataSource.swift:

import UIKit

class myTableViewDataSource: NSObject, UITableViewDataSource, UITableViewDelegate {

    init(str:String) {
        print(str)
    }

    // MARK: UITableViewDataSource
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        print("section")
        return 3
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("row")
        return 5
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! myCustomCell
        print("where's my cell")
        return cell;
    }
}

我试图做的只是让数据源成为另一个类并将它的实例变量分配给我的 tableView。

更新

根据@Rajan Maheshwari 的说法

setup() 的底部添加 tableview.reloadData() 得到正确的部分/行号, 但 "where's my cell" 仍然没有打印出来……因为 cellForRowAtIndexPath 从未执行过。

我这里可能遇到的问题是什么?

最佳答案

这是因为您的 DataModel 是局部变量。将其移至类(class)。例如:

class myTableViewController: UIViewController {
  let myDataSource: myTableViewDataSource
...
  func setup() {
    myDataSource =
...

这种方法称为MVVM 模式。您可以找到有关此模式的信息 here . 此外,您的类(class)应命名为 CamelCase风格。所以请将 my... 更改为 My...

关于ios - Swift 分离 UITableViewDataSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33351999/

相关文章:

ios - 将 Canvas 原型(prototype)转换为 iOS 原生

ios - 读入声音文件,添加回声并写入新的声音文件

ios - Alamofire:无论 timoutIntervalForRequest 如何,1 秒内为 'The request timed out'

ios - UIGestureRecognizer 阻止 TableView 编辑

ios - UITableView 重复 Firebase 数据

ios - 在 Swift 中将数据源分离到另一个类,然后处理数据更改

android - 我可以对其他应用程序使用 Appium 运行测试吗?

objective-c - 调用 AVAudioSession setActive :NO 后恢复 iPod 播放

ios - Swift 中 UITableView 的奇怪行为

swift - 如何在 Swift 中显示 NSData 中的 PDF - 如何将 PDF 保存到文档文件夹 Swift - 如何在 Swift 中通过 WebView 显示保存的 NSData 中的 PDF