问题
I'm trying to create a UITableView to allow the user to enter data, similar to a lot of the settings UITableViews, with some textfields and callouts to other tableviews for checkboxes. For such a common feature in apps, this does not seem to be very straight forward.
I'm having trouble accessing the indexPath.row from my custom UITableViewCell. Here is where I allocate my custom UITableViewCell.
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[TextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
In my TextField class's @implementation, in - (id)initWithStyle: I'm trying to access the indexPath with:
NSIndexPath *indexPath = [(UITableView *)self.superview indexPathForCell:self];
... in order to set the textfield's tag like:
textRow = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 21)];
textRow.tag = [indexPath row];
Could anyone please shed some light on my problem or point me in the direction of creating basic setting-style TableViews programatically.
Thank you
回答1:
I think the problem might be that at the time of initialisation of your cell it hasn't been added to the UITableView - hence self.superview is returning nil.
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[TextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
[cell setTag:indexPath.row];
You will need to add a setTag: method to your TextFieldCellClass. I presume that code was inside cellForIndexPath or whatever, so indexPath will be passed to that method.
The set tag method should look something like this:
-(void)setTag:(int)tag {
textRow.tag = tag;
}
来源:https://stackoverflow.com/questions/5050915/accessing-indexpath-from-custom-uitableviewcell