【问题标题】:Returning two cells in cellForRowAtIndexPath using segmented control使用分段控制返回 cellForRowAtIndexPath 中的两个单元格
【发布时间】:2015-07-01 06:52:42
【问题描述】:

我在两个UITableViews 上方有一个分段控件,其中一个位于另一个之上。当segmentedControl.selectedSegmentIndex == 1 时,其中一个表视图将隐藏。然而,问题是我无法在我的一个cellForRowAtIndexPath 函数中配置第二个表格视图的自定义单元格。我不断收到:Variable 'cell' used before being initialized

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        switch segmentedControl.selectedSegmentIndex {
        case 0:
            var cell = tableView.dequeueReusableCellWithIdentifier("CellOne", forIndexPath: indexPath) as! CellOne

            return cell

        case 1:

            var cellTwo = tableView.dequeueReusableCellWithIdentifier("CellTwo", forIndexPath: indexPath) as! CellTwo

            return cellTwo

        default:
            var cell: UITableViewCell
            return cell
        }


    }

【问题讨论】:

    标签: ios swift uitableview uisegmentedcontrol


    【解决方案1】:

    您有返回的未初始化单元格变量的默认分支。我建议进行如下更改:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let result: UITableViewCell
    
        if (segmentedControl.selectedSegmentIndex == 0) { 
           var cellOne = tableView.dequeueReusableCellWithIdentifier("CellOne", forIndexPath: indexPath) as! CellOne
           //Configure here
           result = cellOne
        } else {
           var cellTwo = tableView.dequeueReusableCellWithIdentifier("CellTwo", forIndexPath: indexPath) as! CellTwo
           //Configure here
           result = cellTwo
        }
    
        return result
    }
    

    【讨论】:

    • 那有什么解决办法?
    • @dprek 我更新了我的答案。我在代码中做了一个假设,总是选择了一些段,所以我们总是显示 CellOne 或 CellTwo,没有任何其他选项。
    • 我将如何配置,即 CellOne 中的标签与 CellTwo 中的 UIImageView?
    • 嘿,这是另一个问题,在您的代码示例中,对配置的引用为零。给我一点时间来更新代码以获取更新的需求。
    • 不,我收到了Missing return in a function expected to return 'UITableViewCell'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 2013-09-24
    • 2021-12-09
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多