簡體   English   中英

找出單元格的索引路徑

[英]Find out indexPath of cell

我有幾個 UITableViewCells 帶有標簽 Test1、Test2、Test3、Test4 和 Test5。 如何找出顯示Test3的單元格的indexPath? 我不想碰手機或做這樣的事情。 感謝您的回答!

細胞:

在此處輸入圖片說明

核心數據模型:在此處輸入圖片說明

創建對單元格的類變量引用,然后在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
    }

在單元格級別這樣做似乎是倒退——您的數據模型(表的UITableViewDataSource )似乎更容易查詢。

如果您有對標簽的引用,則可以使用indexPathForRowAtPoint

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

indexPath其中 indexPath 是可選的。

你是如何填充表格的? 如果您使用 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

然后您可以檢查單元格中標簽的文本,看看它是否符合您的需要。

此方法將檢查 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") 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM