问题
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 UIView
s 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:
In the long run it'll be easier to create a
UITableViewCell
which contains aUITextField
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.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