Table Cell SubView Iteration Not Finding TextField

回眸只為那壹抹淺笑 提交于 2019-12-19 11:52:07

问题


I've created a table where each cell holds both a text label and a text field. I'm adding the textfields as such [cell addSubview:passwordField]; and from a visual perspective they appear and are editable, etc....

The problem arises when I attempt to retrieve the entered values from the textfields. I iterate over the cells and try to grab the subview (IE the textfield), however, my iteration only discovers the text label.

Here is the code I'm using to search:

for(NSInteger i =0; i < [tableView numberOfRowsInSection:0]; i++){
   NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:0];
   UITableViewCell *cell = [tableView cellForRowAtIndexPath:path];
   UIView* subView = [[cell.contentView subviews]lastObject]; // I've also tried object at index here

// Anything beyond this is just matching....

Another approach I took was recursively searching the subviews, but, again that yielded no results.


回答1:


You have added your textField on subView of cell.

[cell addSubview:passwordField];

While you're trying to find it on cell.contentView.
Add your textField as a subView of cell.Contentview

[cell.contentView addSubview:passwordField];

And find it in this way -

for(UIView *view in [cell.contentView subviews])
{
    if([view isKindOfClass:[UITextfield class]])
    {
       UITextField *textField = (UITextField *)view;
       NSLog(@"%@",textField.text);
    }
}



回答2:


Why not have a datasource mapped to the TableView and just retrieve / update the values in the datasource. You can then call reloadRowsAtIndexPaths to load just the row you just changed. Trying to iterate through the TableView rather than just updating the datasource seems very inefficient.




回答3:


Instead of UIView* subView = [[cell.contentView subviews]lastObject]; you can try to find it as:

for(UIView *view in [cell subviews])
{
  if([view isKindOfClass:[UITextfield class]]){
    // view is the reference to your textfield
  }
}

That way you can add other UIViews as subviews and still get the reference of the textfield without having to keep track of its subview index.




回答4:


2 things occur to me:

  1. In the long run it'll be easier to create a UITableViewCell which contains a UITextField which is accessible as a property. You can either use a nib to layout the cell or do it programmatically in the cells init method. This approach will make your code easier to manage.

  2. You need to consider cell reuse. If you are reusing cells (which you should be) then you will need store the fetch the value from the textfield before it is reused.



来源:https://stackoverflow.com/questions/13015348/table-cell-subview-iteration-not-finding-textfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!