【发布时间】:2016-08-21 16:47:07
【问题描述】:
我是 iOS/Swift 开发的新手,在为 UITableView 进行 DataSource 的动态交换时遇到问题 - 请注意,我不是在交换 Delegate,只是交换 DataSource。
我已阅读有关 Stack Overflow 的其他类似问题/回复,但未找到与我的情况相关的问题。通常他们是关于在“viewDidLoad”上设置数据源(例如this one和this one),而我的情况是当用户按下按钮时交换数据源。我的代码中不存在引用问题中的问题。
这是我的代码大纲。我将 buttonPress 方法连接到情节提要中的 TouchUpInside 事件:
class ViewController: UIViewController, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
...
@IBAction func buttonPress(sender: UIButton) {
...
self.tableView.dataSource = DummyDataSource()
self.tableView.delegate = self
self.tableView.reloadData()
}
...
}
...这是我的数据源类:
import UIKit
class DummyDataSource: NSObject, UITableViewDataSource {
let names = ["A", "B", "C"]
func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return names.count
}
func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) as UITableViewCell?
if ( cell == nil ) {
cell = UITableViewCell( style: UITableViewCellStyle.Default,
reuseIdentifier: simpleTableIdentifier)
}
cell!.textLabel?.text = names[indexPath.row]
return cell!
}
}
当我按下按钮时,我可以看到 pressButton 方法被正确调用,但数据没有显示在 tableView 中(没有错误 - 只是没有数据)。请问有什么想法吗?谢谢。
【问题讨论】:
-
使用调试器。你
DummyDataSource的数据源方法被调用了吗? -
您不能只初始化和分配数据源类。创建一个实例,然后分配。
-
@rmaddy - 我只是在我的 DummyDataSource 中的 count 和新单元格方法中添加了一个 print,我看到 count 方法确实被调用了。
-
@nickpharris 我的回答说明了一切。如果需要进一步澄清,只需对答案发表评论即可。
-
欢迎您,您的问题终于解决了。它由下面的@nhgrif 解释..就是这样
标签: ios swift uitableview