找出单元格的 indexPath

Posted

技术标签:

【中文标题】找出单元格的 indexPath【英文标题】:Find out indexPath of cell 【发布时间】:2015-07-02 18:35:16 【问题描述】:

我有几个 UITableViewCells 标签为 Test1、Test2、Test3、Test4 和 Test5。如何找出显示 Test3 的单元格的 indexPath?我不想碰牢房或做类似的事情。感谢您的回答!

细胞:

核心数据模型:

【问题讨论】:

【参考方案1】:

创建对单元格的类变量引用,然后在cellForRow 中将带有“Test3”标签的单元格分配给您的类变量。

var test3Cell: UITableViewCell?

// ...

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

        let cell = ... // Declaration here

        // set up the cell

        if cell.textLabel?.text == "Test3" 
            self.test3Cell = cell
        

        return cell
    

【讨论】:

【参考方案2】:

在单元格级别执行此操作似乎是倒退 - 您的数据模型(表的 UITableViewDataSource)似乎更容易查询。

【讨论】:

我使用 CoreData。 Test1 Test2 Test3 Test4Test5 保存在 name 中(请参阅我的问题中的图片)。你知道如何在没有 indexPath 的情况下从 name 中删除 Test3 吗? 我的 CoreData 已经生锈了,但是查询和删除肯定会更容易。也许看到***.com/questions/6524876/…【参考方案3】:

如果你有标签的引用,你可以使用indexPathForRowAtPoint

let pointInTable = sender.convertPoint(theLabel.bounds.origin, toView: self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(pointInTable)

indexPath 其中 indexPath 是可选的。

【讨论】:

【参考方案4】:

你是如何填充表格的?如果您使用 NSArray.. 中的内容填充 tableview 单元格中的标签,您可以从 Array obj..中的项目索引中找到 indexpath..

如果没有,我能想到的方法是循环遍历tableView中的表格单元格

表格视图响应以下方法 func numberOfSections() -> Int func numberOfRowsInSection(section: Int) -> Int

您可以使用上述信息为每一行创建一个 NSIndexPath 实例 .. NSIndexPath(forRow: , inSection: )

使用获取 UITableviewCell 实例 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

然后你可以检查单元格中的标签文本,看看它是否符合你的需要。

【讨论】:

【参考方案5】:

此方法将检查您当前在 tableview 中的可见单元格并遍历它们以查找文本。

// Swift 1.2
// Store current visable cells in an array
let currentCells = tableView.visibleCells() as Array

 // Iterate through cells looking for a match
 for cell in currentCells 
    println (cell.textLabel?!.text)

    if cell.textLabel?!.text == "Test 3" 
        println("Test 3 Found")
    



// Swift 2.0
// Store current visable cells in an array
let currentCells = tableView.visibleCells

// Iterate through cells looking for a match
for cell in currentCells where cell.textLabel?.text == "Test 3" 
    print("Test 3 found") 

【讨论】:

感谢您的回答!我在这行代码中遇到错误:for cell in currentCells 它说:'() -> [AnyObject]' does not have a member named 'Generator'。你知道为什么吗? 我的错误,我没有使用 Swift 1.2 测试上述内容。我现在已经修改了帖子以考虑到这一点。

以上是关于找出单元格的 indexPath的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 给定一个2D板和一个单词,找出该单词是否存在于网格中。该单词可以由顺序相邻的单元格的字母w构成

怎样取得dataTable中某一单元格的值

如何在 uicollectionview 单元格中使用 uibutton 操作并获取单元格的内容

如何将单元格而不是单元格的值传递给 LibreOffice 函数?

带有多个值的单元格的 Microsoft Excel 电子表格筛选器

如何使用 vba 在 Excel 2007 中找到条件格式单元格的填充颜色值?