我只是尝试使用从数组中提取的新项目重新加载 TableView,而 tableView 不会重新加载新项目。这是代码。有什么帮助吗?
导入 UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var myTableView: UITableView!
@IBAction func reloadData(sender: UIButton) {
tableData = newItems
self.tableViewController.tableView.reloadData()
}
var items = ["AAA", "BBB"]
var newItems = ["XXX", "YYY"]
var tableData = [String]()
var tableViewController = UITableViewController(style: .Plain)
override func viewDidLoad() {
super.viewDidLoad()
tableData = items
var tableView = tableViewController.tableView
tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)as UITableViewCell
cell.textLabel?.text = self.tableData[indexPath.row]
return cell
}
}
最佳答案
您的代码中有很多错误,这是您完整的工作代码:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var myTableView: UITableView!
var items = ["AAA", "BBB"]
var newItems = ["XXX", "YYY"]
var tableData = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableData = items
myTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
myTableView.delegate = self
myTableView.dataSource = self
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
cell.textLabel?.text = tableData[indexPath.row]
return cell
}
@IBAction func reloadData(sender: AnyObject) {
tableData = newItems
self.myTableView.reloadData()
}
}
将你的代码与这段代码进行比较,你就会明白你做错了什么。
HERE是更多信息的示例项目。
关于ios - TableView 不重新加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32537123/