开发者

cellForRowAtIndexPath inserting in array

I'm getting a weird issue. I have a custom UITableViewCell and each cell has a UIButton and UITextField. When the button is clicked, it changes the textfield value to some constant.

Now in the cellForRowAtIndexPath method I have this:

    folderTitleTextView.tag=indexPath.row;
    [arrayOfTextFields insertObject:folderTitleTextView atIndex:indexPath.row];
    NSLog(@"indexpath.row:%i", indexPath.row);
    NSLog(@"text fields count %i", [arrayOfTextFields count]);

So if I have two cells, then every time I reload the table, it adds two more objects to the arrayofTextFields, even thou开发者_开发百科gh it should replace the existing ones. So if I have two cells and I reload the table 3 times, then for some reason arrayOfTextFields count is 8.


This folderTitleTextView.tag=indexPath.row; is not a good idea because everything starts with a tag of 0, so when accessing views with viewWithTag:0 or when setting up the row 0, you will get weird results.

I would suggest also checking the number of items in arrayOfTextFields and use [arrayOfTextFields replaceObjectAtIndex:indexPath.row withObject:folderTitleTextView]; or [arrayOfTextFields insertObject:folderTitleTextView atIndex:indexPath.row]; depending on the current count for arrayOfTextFields

Try this:

folderTitleTextView.tag = (indexPath.row + 100);
if ([arrayOfTextFields count] <= indexPath.row) {
    [arrayOfTextFields insertObject:folderTitleTextView atIndex:indexPath.row];
} else {
    [arrayOfTextFields replaceObjectAtIndex:indexPath.row withObject:folderTitleTextView];
}
NSLog(@"indexpath.row:%i", indexPath.row);
NSLog(@"text fields count %i", [arrayOfTextFields count]);


The question is what are you trying to do?

Right now you add the textView to an array each time a cell is displayed.

If you have 1 cell you have 1 textView in the array because cellForRowAtIndexPath: was called 1 time.
If you add another cell so you have 2 total cell cellForRowAtIndexPath will be called another 2 times and it will add 2 textViews to the array that already has one -> 3
If you add another cell cellForRowAtIndexPath adds 3 more textViews to the 3 that are already there -> 6

So much for the explanation of your results.


My suggestion is to get rid of that array and get rid of the tag, most likely those are not needed at all.

you can access the cell with something like this:

- (IBAction)buttonPressed:(UIButton *)sender {
    UIView *contentView = [sender superview];
    UITableViewCell *cell = (UITableViewCell *)[contentView superview];
    // you should assign a tag to the textField of your cell. Use the same tag for each textView in all cells. 
    UITextField *textField = (UITextField *)[cell viewWithTag:42];
    textField.text = @"Foo";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜