【问题标题】:Get indexpath outside of any tableView function在任何 tableView 函数之外获取索引路径
【发布时间】:2015-10-20 20:55:36
【问题描述】:

也许我的问题很简单,但我太愚蠢了,无法理解。 我的问题是我想在

之外访问 indexPath
overide func tableView(...)

所以我在我的 TableView 类中,并且有一个单独的类,例如:

func setColor()
{
...
}

在这个类中,我想访问 indexPath。我该怎么做?

【问题讨论】:

  • 将 indexPath 作为参数传递。
  • 你需要明确你的目标是什么。这个setColor 方法是如何以及何时被调用的?它在哪个班级?
  • 我在 TableView 类中,在另一个类之外我调用这个函数,名为 setColor。
  • 所以,其他一些类调用setColorsetColor 需要索引路径做什么?它设置的颜色是什么?
  • 我想在 tableView 的选择移动到另一个单元格时调用这个类。我不能用 didSelecrRowAtIndexPath 做到这一点,因为有时单元格颜色应该改变,尽管如果用户没有点击单元格,就像一个 segue。

标签: ios swift tableview nsindexpath


【解决方案1】:

indexPath 是一个对象,它被创建并传递给 UITabelViewDelegate 或 UITableViewDataSource 方法。它可以让您指示加载/点击了哪个单元格等。

因此您将无法从外部访问此对象。如果您想更改单元格的某些内容,例如backgroundColor 您应该将颜色存储在属性中,更改此属性并强制重绘。在创建单元格的委托方法中,使用此属性设置颜色。

这是一些示例代码。

视图控制器

class TestTableViewController: UIViewController, UITableViewDelegate {

    // Store array of color
    var backColors = [UIColor.redColor(), UIColor.greenColor()]


    // Method which changes color
    func setColor(row: Int, color: UIColor) {
        backColors[row] = color
    }

    // Override draw
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // Create your cell
        // ...

        // Set color
        cell.backgroundColor = backColors[indexPath.row]
    }
}

【讨论】:

  • 是的,我想更改单元格的背景颜色。所以我应该强制重新加载 tableView,然后在 cellforRowAtIndexPath 中设置颜色?
  • 我会这样做。将颜色存储在控制器中,强制重绘并在 cellforRowAtIndexPath 方法中使用此颜色。
猜你喜欢
  • 1970-01-01
  • 2018-10-08
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
  • 2015-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多