Сохраните UITextField внутри UITableViewCell в NSMutableArray - PullRequest
0 голосов
/ 22 марта 2012

Хорошо, я знаю, что этот вопрос задавался ранее, но у меня проблема другая, чем у других.

У меня есть текстовое поле внутри настраиваемой ячейки табличного представления, которое мне нужно сохранить в массив послецифровая клавиатура отклонена.Поскольку на цифровой клавиатуре нет кнопки «Готово», мне пришлось реализовать сенсорное событие, чтобы закрыть цифровую клавиатуру.Это означает, что мой -textFieldDidEndEditing не запускается.Вот соответствующий код:

в моем viewController.h

itemData *tempItem; //A custom object    
UITableView *itemsListTable;
NSMutableArray *listData;

в моем viewController.m

    - (UITableViewCell *)tableView:(UITableView *)tableView
             cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {

       static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";


        UITableViewCell *cell = [itemsListTable
                                 dequeueReusableCellWithIdentifier:SimpleTableIdentifier];

        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
                                          reuseIdentifier:SimpleTableIdentifier];


        NSInteger row = indexPath.row;
        tempItem = [listData objectAtIndex:row];
        cell.textLabel.text = [tempItem getItemName];


        UITextField *quantityTextField = [[UITextField alloc] initWithFrame:CGRectMake(275, 8, 35, 27)];
        quantityTextField.keyboardType = UIKeyboardTypeNumberPad;
        quantityTextField.borderStyle = UITextBorderStyleRoundedRect;
        quantityTextField.returnKeyType = UIReturnKeyDone;
        quantityTextField.text = [NSString stringWithFormat:@"%d", tempItem.getItemQuantity];
        quantityTextField.textAlignment = UITextAlignmentCenter;


        [cell addSubview:quantityTextField];
        } 


        return cell;

    }

-(void)touchesEnded: (NSSet *)touches withEvent: (UIEvent *)event {
[[self itemsListTable] endEditing:YES];
    }
- (void)textFieldDidEndEditing:(UITextField *)textField {

    UITableViewCell *cell = (UITableViewCell*)textField.superview;

    NSIndexPath *indexPath = [self.itemsListTable indexPathForCell:cell];

    tempItem = [listData objectAtIndex:indexPath.row];

    NSLog(@"Did End Editing");
    [tempItem setItemQuantity:[textField.text intValue]]; //save textfield to object as intValue

    [listData replaceObjectAtIndex:indexPath.row withObject:tempItem]; //save object to array
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [listData removeObjectAtIndex:indexPath.row];
        [itemsListTable reloadData];
    }    
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    numberOfItems.text = [NSString stringWithFormat:@"%d",listData.count];

    return [self.listData count];
}

1 Ответ

2 голосов
/ 22 марта 2012

Когда ваше событие касания отклоняет клавиатуру, также вызовите [self textFieldDidEndEditing:], или, если вам нужно узнать, какое текстовое поле имело фокус в последний раз, сохраните ссылку, определив объект UITextField, который вы установили для текущего текстового поля, которое имеет первый респондент в делегатной функции textFieldDidBeginEditing. Как это:

//In .h
UITextField * txtReference;

//In .m
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    txtReference = textField;
}

//In the function that dismisses the keyboard put:
[self textFieldDidEndEditing:txtReference];
...