How To get values of textfields from a UITableViewCell?

后端 未结 6 1638
天命终不由人
天命终不由人 2021-01-01 02:13

So I have thisUITableView cell that has 4 UITextField, and I want to get their values on button click.

This code does not retrieve any valu

6条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-01 02:38

    OK. You are dequeueing a tableViewCell when you press on a button.

    let cell = self.myTableView.dequeueReusableCell(withIdentifier: "manualAddC1") as! AddFriendC1Cell
    

    I believe that you want to get a reference to an existing tableViewCell like this:

       if let cell = tableView.cellForRow(at: indexPath) as? AddFriendC1Cell {
            // do what you need with cell
        }
    

    Even though this would work, I wouldn't suggest this approach. What if user is using a smaller-screen phone like iPhone 4 and some cells are not visible on the screen? I think that in that case tableView.cellForRow would return nil for non-visible cell.

    I would suggest implementing textField:shouldChange in each cell with text field with a delegate to the tableView's viewController. When text is changed in the cell, delegate should propagate the change to the viewController which would save the value in an instance variable.

    Then, when you press on the button, you would simply take values from instance variables.

提交回复
热议问题