UITableViewCells没有第一次显示

时间:2015-06-02 22:00:55

标签: ios uitableview

我正在尝试使用iOS 8,Swift和Xcode 6.3创建自动完成程序

我有一个问题,我正在努力解决,但我放弃了...我希望有人可以在这里提供帮助。问题是,当初始UITableViewCell为空时,(自定义)dataSource不会显示。将数据添加到datasource并重新加载tableView时,单元格应该显示,但它们不会...至少,它们第一次没有...第二次,它们是DO ...当我使用非空数据初始化表时,不会发生此问题。我想dequeueReusableCellWithIdentifier出了点问题。一开始,没有找到可重复使用的细胞,或者什么。但我不知道为什么......

相关代码,在ViewController.swift中:

// filteredWords is a [String] with zero or more items

@IBAction func editingChanged(sender: UITextField) {
    autocompleteTableView.hidden = sender.text.isEmpty
    filteredWords = dataManager.getFilteredWords(sender.text)
    refreshUI()
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! AutocompleteTableViewCell
    cell.title.text = filteredWords[indexPath.row]
    return cell
}

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

func refreshUI() {
    self.autocompleteTableView.reloadData()
}

我在github上创建了一个示例项目:

https://github.com/dirkpostma/swift-autocomplete

和YoutTube上的电影一起显示出现了什么问题:

https://www.youtube.com/watch?v=ByMsy4AaHYI

任何人都可以看一下并发现错误......?

提前致谢!

2 个答案:

答案 0 :(得分:5)

你不小心隐藏了你的牢房。

  1. 打开Main.storyboard
  2. 选择单元格
  3. 取消选中隐藏
  4. 旁注:至于为什么第二次显示隐藏的单元格?这似乎是一个错误。它应该仍然是隐藏的(打印cell.hidden,尽管在屏幕上显示文本,但请注意它总是正确的。)

答案 1 :(得分:1)

我认为您需要更改代码。查看以下代码。这是因为如果你记得在Objective C中你需要检查Cell是否为零然后初始化它。重用标识符通常重用已经创建的单元格,但在第一次启动时,这不起作用,因为没有要使用的Cell。您当前的代码始终假定您正在使用创建(重新使用)单元格!在声明中,所以如果使用可选(?),它可以为null,然后您可以创建单元格

    var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? AutocompleteTableViewCell

    if cell == nil 
    {
        //You should replace this with your initialisation of custom cell
        cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL") 

    }

    cell.title.text = filteredWords[indexPath.row]
    return cell
相关问题