简体   繁体   中英

Check textField in each row of tableView

This is the situation : I have a tableView with 3 rows. In this tableView, there is one tableVIewCell prototype with a textField. This textField is used in each row of tableView (differently). My question is : how to check if each textField is empty ? I guess an If Statement but I don't understand how to check all the textFields separately. Anyone could help me, please ?

An example of my tableView: http://imagizer.imageshack.us/a/img540/2130/UsUNO3.png

I've had to do this exact thing in the past, here's the method I used:

for index in 0...(cellCount - 1) {

            var indexpath = NSIndexPath(forRow: index, inSection: 0)
            if let cellAtIndex = tableView.cellForRowAtIndexPath(indexpath) as? ContestantsTableViewCell {
                var newContestantString = cellAtIndex.contestantNameField.text

                if !newContestantString.isEmpty {
                    contestants.append(newContestantString)
                }
            }
        }

I just get the cell at the index path using cellForRowAtIndexPath and get the property from the cell by casting it as my custom type.

如果您知道始终只显示3个单元格,则可以保留对每个单元格和每个单元格textField的引用,并在需要时检查其长度。

Your textfield can be checked in each row by using indexpath.row(Tableview)

if(indexpath.row == 0){
    if(cell.textfield.text == "")
    {
      //1st textfiled empty
    }

}
else if(indexpath.row == 1){
  if(cell.textfield.text == "")
    {
      //2nd textfiled empty
    }
}
else if(indexpath.row == 2){
 if(cell.textfield.text == "")
    {
      //3rd textfiled empty
    }
}

Ok you can create the function like below.You can use this function for any number of cell do not use if else condition. You can also use this function as textField Validation.

func getCellsDataOn() -> Bool {
        for section in 0 ..< self.tableView.numberOfSections {
            for row in 0 ..< self.tableView.numberOfRows(inSection: section) {
                let indexPath = NSIndexPath(row: row, section: section)
                let cell = self.tableView.cellForRow(at: indexPath as IndexPath) as! YourCell
                if (cell.txtField!.text! != "") {
                    print("Not Empty")
                    //Handle your function 
                }else {
                    print("Empty")
                    return false
                }
            }
        }
        return true
    }

Hope this help Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM