【问题标题】:UITableView reloadData() Swift2 not reloading dataUITableView reloadData() Swift2 不重新加载数据
【发布时间】:2016-07-20 09:46:37
【问题描述】:

我是 Swift 的新手,试图在 UITableView 中显示乘法表并根据滑块值更改数据。模型在更改滑块位置时更新,但 tableView 未显示表格当前可见部分的更新。在滚动期间添加或删除新行时会发生更新。一些代码:

class ViewController: UIViewController, UITableViewDelegate {

@IBOutlet var slider: UISlider!
@IBOutlet var tableView: UITableView!

let maxCount = 50
var multiplierArray: [String] = []

override func viewDidLoad() {
    super.viewDidLoad()
    let number: Int = Int(slider.value)
    populateData(number)
}

func populateData(number: Int) {
    var i = 0
    multiplierArray.removeAll()
    while i < maxCount {
        let table = i + 1
        let str = "\(number) x \(table) = \(table * number)"
        print(str)
        multiplierArray.append(str)
        i += 1
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return multiplierArray.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
    cell.textLabel?.text = multiplierArray[indexPath.row]
    print("cellForRowAtIndexPath called")
    return cell
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int{
    return 1
}

@IBAction func sliderValueChanged(sender: UISlider) {
    let number: Int = Int(slider.value)
    populateData(number)
    tableView.reloadData()
    print("slider value changed" + String(number))
}
}

我阅读了很多关于这个问题的帖子,但无法在上面的代码中找出问题所在。我的理解是 tableView.reloadData() 应该在底层模型发生更改时更新视图,例如 android 中的 notifyDataSetChanged()。是不是缺少了一些tableView的功能?

【问题讨论】:

  • 您能否向我们展示您是否将表格视图的委托和数据源分配给您当前的视图控制器?

标签: ios uitableview swift2


【解决方案1】:

你的ViewController类需要实现UITableViewDataSource协议,这里不需要实现UITableViewDelegate。 并且需要在viewDidLoad函数中赋值(例如):

override func viewDidLoad() {
    super.viewDidLoad()
    let number: Int = Int(slider.value)
    populateData(number)
    tableView.datasource = self;
}

快速说明: UITableViewDatasource 负责用数据填充UITableViewUITableViewDelegate 关心单元格高度和选择状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多