iosuitableviewuitextfielduialertviewuialertviewdelegate

Passing text from a UIAlertView text field to a custom cell label


I have an application that pulls information from a SQLite database and populates the cells within a TableView. However, I want the user to be able to click a cell and then be able to edit the content within that cell via the AlertView. The following is part of my code:

    //Set up cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:    (NSIndexPath *)indexPath
{
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];


cell.textLabel.text = [resultSet objectAtIndex:indexPath.row];

return cell;
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{

CustomCell *cell = [tableView cellForRowAtIndexPath:indexPath];

UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Question" message:@"Please enter a new question" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
av.alertViewStyle = UIAlertViewStylePlainTextInput;
txtNewQuestion = [av textFieldAtIndex:0];
txtNewQuestion.clearButtonMode = UITextFieldViewModeWhileEditing;
av.delegate = self;
[txtNewQuestion setPlaceholder:@"new Question"];
[av show];
[self.txtNewQuestion becomeFirstResponder];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex  {



if (buttonIndex == 1) {

    CustomCell *cell;
    enteredQuestion = txtNewQuestion.text;
    cell.customLabel.text = enteredQuestion;
    NSLog(@"%@", enteredQuestion);
    NSLog(@"%@", cell.customLabel.text);

}
[self.tableView reloadData];

}

Any assistance would be greatly appreciated. Thanks.


Solution

  • I would use didSelectRowAtIndexPath instead, and I sometimes like to use tags :

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
    {
        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Question" message:@"Please enter a new question" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
        av.alertViewStyle = UIAlertViewStylePlainTextInput;
        av.delegate = self;
        av.tag = [indexPath row];
        [av show];
    }
    
    -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
    {
        if (buttonIndex == 1) {
            [resultSet replaceObjectAtIndex:alertView.tag withObject:[alertView textFieldAtIndex:0].text];
            [table reloadData];
        }
    }