How can I loop through UITableView's cells?

Viewed 69060

I have n sections (known amount) and X rows in each section (unknown amount. Each row has a UITextField. When the user taps the "Done" button I want to iterate through each cell and do some conditional tests with the UITextField. If the tests pass data from each cell is written to a database. If not, then a UIAlert is shown. What is the best way to loop through the rows and if there is a more elegant solution to this please do advise.

9 Answers

for xcode 9 use this - (similar to @2ank3th but the code is changed for swift 4):

let totalSection = tableView.numberOfSections
for section in 0..<totalSection
{
    print("section \(section)")
    let totalRows = tableView.numberOfRows(inSection: section)

    for row in 0..<totalRows
    {
        print("row \(row)")
        let cell = tableView.cellForRow(at: IndexPath(row: row, section: section))
        if let label = cell?.viewWithTag(2) as? UILabel
        {
            label.text = "Section = \(section), Row = \(row)"
        }
    }
}
for (UIView *view in TableView.subviews) {
    for (tableviewCell *cell in view.subviews) {
       //do
    }
}

swift 5:

guard let cells = self.creditCardTableView.visibleCells as? [CreditCardLoanCell] else {
            return
        }
        
  cells.forEach { cell in
     cell.delegate = self
   }
Related