【问题标题】:Swift separated UITableViewDataSourceSwift 分离 UITableViewDataSource
【发布时间】:2016-01-25 22:06:43
【问题描述】:

我的项目中有 4 个文件:

  • myTableViewController.swift
  • myTableViewDataSource.swift
  • myCustomCell.swift
  • myCustomCell.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;
    }
}

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

更新

根据@Rajan Maheshwari

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

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

【问题讨论】:

  • 在设置函数中。,只需在最后一行重新加载表格。可能有效吗?
  • @RajanMaheshwari 打印结果正确!但我的手机仍然没有出现。
  • 在 myTableViewDataSource.swift tableView.registerNib(UINib(nibName: "myCustomCell", bundle: nil), forCellReuseIdentifier: "myCell") 中注册你的单元格并告诉结果。
  • @RajanMaheshwari 不工作。奇怪的是没有调用所需的cellForRowAtIndexPath

标签: ios swift uitableview model-view-controller


【解决方案1】:

这是因为您的 DataModel 是局部变量。将其移至班级级别。例如:

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

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

【讨论】:

  • 是的。你说的对。让他们达到班级水平解决了问题
  • 完美运行!是的,我用 CamelStyle 命名了我原来的课程,谢谢提醒 :)
【解决方案2】:

原因如下:在您的 UI 设计文件(故事板或 XIB)中,您的表视图有一个条目 dataSource。它默认为视图控制器。

如果您想更改它,请将您的数据源类添加为对象。从插座拖动连接。

如果不这样做,则很难覆盖此设置。

【讨论】:

  • 我猜是在viewDidLoad设置函数代码中改变了datasource
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多