ios - 在任何 tableView 函数之外获取索引路径

标签 ios swift tableview nsindexpath

也许我的问题很简单,只是我太笨了,听不懂。 我的问题是我想访问 indexPath 之外的

overide func tableView(...)

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

func setColor()
{
...
}

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

最佳答案

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

所以你将无法从外部访问这个对象。如果你想改变一个单元格的某些东西,例如backgroundColor 您应该将颜色存储在属性中,更改此属性并强制重绘。在创建单元格的委托(delegate)方法中,使用此属性设置颜色。

这是一些示例代码。

View Controller

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]
    }
}

关于ios - 在任何 tableView 函数之外获取索引路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33246629/

相关文章:

objective-c - NSString 在发布时崩溃

ios - 如何以编程方式检测 iPhone 6 & 6 Plus 查看模式

swift - 我如何使用 Swift 3 scheduleRepeating?

iphone - 登录 iPhone 的 Facebook 设置覆盖 FacebookSDK 共享

swift - 在 UICollectionView 中重新加载数据

android - 在 Android 中添加两个 View

ios - 一些具有动态高度的表格 View 单元格,其他具有固定高度

iOS - 使用 Access 数据库和共享点来推送和拉取数据

ios - UINavigationViewController 中的大量 SceneKit 场景需要很长时间才能解除分配

ios - 选择单元格行而不是复选按钮在 UITableView 中进行复选/取消复选标记