我的项目中有 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/