开发者

UITextView in UITableViewCell - Problem with Tags

开发者 https://www.devze.com 2023-04-01 18:31 出处:网络
i have a Grouped TableView with textfields in the UITableViewCells. - (UITableViewCell *)tableView:(UITableView 开发者_开发百科*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath

i have a Grouped TableView with textfields in the UITableViewCells.

- (UITableViewCell *)tableView:(UITableView 开发者_开发百科*)tableView cellForRowAtIndexPath:(NSIndexPath     *)indexPath
{
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

}


if(indexPath.section < 6) {
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 10,580, 31)];
    textField.tag = indexPath.section + 22;
    textField.delegate = self;
    [cell.contentView addSubview:textField];
    [textField release];
}
return cell;
}

So when i press the Save Button, the saveItem Method is called:

- (void)saveItem {
    NSMutableArray *textFieldArray = [[NSMutableArray alloc] init];
    for (int i = 0; i <6; i++) {
        [textFieldArray addObject:(UITextField *)[self.view viewWithTag:22+i]];
    }
...
}

I can change the values of the first 4 TextFields without a problem. they are also saved, but when i change a value in the 5th or 6th Textfield, my app crashes and i get an error:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSMutableArray insertObject:atIndex:]: attempt to insert nil object at 0'

Any suggestions?

Thanks so far.


I think the problem is in that: not all sections are displayed when you tap Save button. So when you try to access view with tag 5 and 6 they are nil because they are not displayed and so were't added (or were removed) from your view.

To test this just try to scroll to bottom of your tableView and try to tap Save button.


1.what ever your trying to access that object is unavailable to you.which means [self.view viewWithTag:22+i] giving nil.

2.tableview wont allocate memory to all the cells.it allocates memory only for which you can visible.

3.once scroll your tableview and once see the 6th section then press the save button your app will not be crash.


Just need to modify your code

if(indexPath.section <= 6) {     
     UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 10,580, 31)];     
     textField.tag = indexPath.section + 22;     
     textField.delegate = self;     
     [cell.contentView addSubview:textField];     
     [textField release]; 
}


Also, ty not to create the textField in your cellForRowAtIndexPath. You should create it in your init or viewDidLoad methods.

0

精彩评论

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