Search code examples
swiftuitextfielduicollectionviewviewwithtag

SWIFT... how to loop through UIcollectionView, and getting values from the textfield into an array


so i have given the textfields a tag of 10 i want to loop through the cells of the collection view and get the values of the textfield and store them into an array... here is some code.......

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

    let cell1 =  collectionView.cellForItemAtIndexPath(indexPath)

    let textbox1 = cell1?.viewWithTag(10) as? UITextField

    print(indexPath.row)

print(textbox1?.text)

}

if I select the cell the right text is shown, I will eventually have a button, when clicked id want it to loop though all of the cells and store it into an array(which i can do). i need a way to loop through the cells using the index path and storing the textfield data, any help would be much appreciated


Solution

  • Method 1:

    But it only give visible Cells textField values

    for item in self.collectionView!.visibleCells() as! [CollectionViewCell] {
            var indexpath : NSIndexPath = self.collectionView!.indexPathForCell(item as CollectionViewCell)!
            var cell : CollectionViewCell = self.collectionView!.cellForItemAtIndexPath(indexpath) as! CollectionViewCell
            println(cell.textField1.text)
        }
    

    Method 2:

    globally declare a mutableArray

    var arrayCellsTextFields : NSMutableArray = []
    

    in cellForItemAtIndexPath

    cell.textField1.tag  = indexPath.row;
    if(arrayCellsTextFields .containsObject(cell.textField1)==false)
    {
       arrayCellsTextFields .addObject(cell.textField1)
    }
    

    Array contain ur textFields object, you can identify the textfield with its tag, i.e., cell.textField1.tag & indexPath.row are same

    Method 3:

    in cellForItemAtIndexPath

    cell.textField1.tag  = indexPath.row;
    cell.textField1.delegate = self;
    

    using the textField delegate textFieldDidEndEditing u will get values in textField