tableView 屏幕外的单元格在访问时返回 nil,swift

cells off the screen in tableView are returning nil when accessed, swift

我试图在按下按钮时隐藏第 1 部分中的单元格。

当我只有几行并且第 1 部分中的所有行都可见时,我的代码工作正常但是当第 1 部分有更多行并且其中一些不在屏幕上时(您必须向下滚动才能看到它们)我的代码在展开 Optional 值时因意外发现 nil 而崩溃。

    func Action(sender: UIButton){

    var i = 0;
    var numberOFRows = Int(self.tableView.numberOfRowsInSection(1))

    for item in cellItemArray{
        if i < numberOFRows{

            let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: i++, inSection: 1)) as TableViewCell  // crashes here

            cell.layer.hidden = true;
        }
    }

}

如果隐藏所有单元格,也许可以创建一个新值

var control = 1

然后如果您按下按钮隐藏所有单元格,将控制值从 0 更改为 1 并且

@IBAction func Button(sender: AnyObject) {
    self.tableView.reloadData()
    control = 1
}

并且您可以使用 Control 语句 if,"cellForRowAtIndexPath" 方法控制它,

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
    cell.textLabel?.text = "\(cellItemArray[indexPath.row])"
    // Configure the cell...
    if control == 1{

        cell.layer.hidden = true

    }
    return cell
}