表视图.重新加载数据() 表未更新



该表不显示更新的数组以返回到单元格。当我启动应用程序时,我得到空白单元格。所有权限均已在情节提要中授予。我到处都尝试了tableView.reloadData(),但似乎也无法使其工作。如果有人能解释我哪里出了问题,那真的会帮助我变得更好。

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var slider: UISlider!
@IBAction func sliderSelector(_ sender: Any) {
tableGenerate()
}
var arrayTable = [Int]()
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayTable.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style:UITableViewCellStyle.default, reuseIdentifier: "Cell")
cell.textLabel?.text = String(arrayTable[indexPath.row])
tableView.reloadData()
return cell
}
func tableGenerate () {
var tableMultiplier = 1
while tableMultiplier <= 50 {
arrayTable.append(tableMultiplier * Int(slider.value))
tableMultiplier += 1
print(arrayTable)
}
}

像这样添加表视图的出口并与故事板中的表连接-

@IBOutlet weak var tableView1: UITableView!

将代码更改为此 -

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var tableView1: UITableView!
@IBAction func sliderSelector(_ sender: Any) {
tableGenerate()
}
var arrayTable = [Int]()
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayTable.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style:UITableViewCellStyle.default, reuseIdentifier: "Cell")
cell.textLabel?.text = String(arrayTable[indexPath.row])
return cell
}
func tableGenerate () {
var tableMultiplier = 1
while tableMultiplier <= 50 {
arrayTable.append(tableMultiplier * Int(slider.value))
tableMultiplier += 1
}
print(arrayTable)
tableView1.reloadData()
}

通过在cellForRowAt中调用tableView.reloadData(),可以创建一个无限循环,因为reloadData()会自动调用cellForRowAt。您需要在tableGenerate()内移动reloadData(),因为只有在数据源更改时才应调用它。

您还需要在Storyboard中为您的表视图创建一个 IBOutlet。由于您没有使用UITableViewController,您需要手动执行此操作。

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var slider: UISlider!
@IBAction func sliderSelector(_ sender: Any) {
tableGenerate()
}
var arrayTable = [Int]()
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayTable.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style:UITableViewCellStyle.default, reuseIdentifier: "Cell")
cell.textLabel?.text = String(arrayTable[indexPath.row])
return cell
}
func tableGenerate () {
var tableMultiplier = 1
while tableMultiplier <= 50 {
arrayTable.append(tableMultiplier * Int(slider.value))
tableMultiplier += 1
print(arrayTable)
}
tableView.reloadData()
}
}

忘了创建表格出口!我也忘了用数组滑块重置数组,现在它工作正常

最新更新