【问题标题】:Switch statement case not being called when using UITableView使用 UITableView 时未调用 switch 语句案例
【发布时间】:2016-02-28 01:27:24
【问题描述】:

我有一个TableViewController 和一个UITableView,视图控制器类有一个名为isFolder 的变量。

ViewController 中,我使用一个switch 语句来确定我应该使用哪个变量selectedFolder1selectedObjects。每个变量都是一个 NSManagedObject 子类,并且有一个返回数组的arrayOfItems 方法。

当准备 segue 时,isFolder 的值取决于传递的数据。

这一切都很好。问题是当数据传递时,我使用 switch 语句来填充表。当 switch 语句 case 是 true for isFolder 时,它不是为 cellForRowAtIndexPath 表函数调用的,而是为 numberOfRowsInSection 调用的。但是,当我在关闭模式视图后重新加载视图时,会出现数据。

例如

这个函数工作正常,并且调用了 switch 语句 case true。

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    switch isFolder {
    case true: print("no. of cells for folder"); return self.selectedFolder.arrayOfItems.count
    case false: print("no. of cells for object"); return self.selectedObject.arrayOfItems.count
    }
}

但是,以下用于填充 tableview 单元格的函数不会调用 switch 语句 case for true。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell
    let color = colorWheel()
    cell.selectionStyle = .None

    // Configure the cell...

    cell.backgroundColor = color.white

    switch isFolder {
    case true:
        print("Using selected Folder")
        cell.textLabel?.text = selectedFolder.arrayOfItems[indexPath.row].title

    case false:
        print("Using selected Object")
        cell.textLabel?.text = selectedObject.arrayOfItems[indexPath.row].title

    }
    return cell
}

当案例为假时,一切正常,数据首次显示。如前所述,如果 switch 语句为真,则该表显示数据,但仅当我关闭模式视图并发布通知以调用 self.table.reloadData() 时。我确实在viewDidLoad 中调用了表格方法reloadData,但这没有任何作用。

有人有什么建议吗?

【问题讨论】:

  • 如果你在tableView(_:numberOfRowsInSection) 内放置一个断点,那么self.selectedFolder.arrayOfItems.count 的值是多少?如果为零,则不会调用cellForRowAtIndexPath
  • 哦,对了,它是 0。我想因为在 numberOfRows 中调用 print 的次数与数组计数相同,所以应该没问题。我现在在调用prepareForSegue 时所做的事情我重新生成了数组。

标签: ios swift uitableview


【解决方案1】:

确保在对 UITableView 对象调用 reloadData() 之前填充数据对象。否则,如果numberOfRowsInSections返回0,则cellForRowAtIndexPath不会被调用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 1970-01-01
    • 2014-01-03
    • 2015-12-06
    • 1970-01-01
    • 2021-03-22
    • 2015-06-21
    相关资源
    最近更新 更多