Извлечение значений из textField в пользовательскую ячейку iPhone - PullRequest
2 голосов
/ 08 сентября 2011

У меня есть пользовательская ячейка в табличном представлении, см. Ниже.

enter image description here

В моей пользовательской ячейке есть два textFields txt1 и txt2, как показано ниже

enter image description here

Как я могу получить доступ к значениям, которые я ввожу в каждое из текстовых полей, чтобы я мог добавить значения в отдельные массивы ...

кнопка «Addset» будет увеличивать количество секций сгруппированной таблицы. Здесь будет увеличен еще один набор.

мой код представления таблицы выглядит следующим образом.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *cellID= @"catogoryCell";
    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellID];

    if(cell==nil)
    {
        NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:nil options:nil];

        for(id currentObject in nibObjects)
        {
            if([currentObject isKindOfClass: [CustomCell class]])
            {
                cell = (CustomCell *)currentObject;
            }
        }
    }

    //cell.txt1.text = @"0"; 

    return cell;
}

Спасибо всем ..

Ответы [ 2 ]

2 голосов
/ 08 сентября 2011

Ячейки можно использовать повторно, поэтому им нужен более настойчивый способ хранения информации.

Метод 1: Вы можете хранить несколько UITextField объектов в массиве, если вы не хотите повторно использовать текстовые поля, а на cellForRowAtIndexPath вам нужно всего лишь установить текстовые поля в их ячейках, например:

cell.txt1 = [textFieldsArray objectAtindex:indexPath.section*2];
cell.txt2 = [textFieldsArray objectAtindex:indexPath.section*2+1]; //txt1 and txt2 properties should have assign

Метод 2 : Если вы также хотите повторно использовать текстовые поля, я предлагаю использовать массив с изменяемыми словарями, каждый словарь содержит «настройки» для ячейки. Текстовые поля будут полностью управляться пользовательской ячейкой (например, при значениях UIControlEventValueChanged update update @ "txt1" или @ "txt2" из словаря, присоединенного к ячейке).

///somewhere in the initialization (in the class holding the tableview)
contentArray = [[NSMutableArray alloc] init];

///when adding a new cell (e.g: inside the 'Add set' action)
[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"", @"txt1", @"", @"txt2", nil]];
//add a new cell to the table (the same way you do now when tapping 'Add set')

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ...
     [cell attachDictionary:[contentArray objectAtIndex:indexPath.section]];
    return cell;
}

///anywhere where you'd like to access the values inserted inside a cell
NSMutableDictionary *cell3Content = [contentArray objectAtIndex:3];
NSString *text1 = [cell3Content valueForKey:@"txt1"];
NSString *text2 = [cell3Content valueForKey:@"txt2"];

///CustomCell.m
-(id)initWithCoder:(NSCoder *)decoder{
    self = [super initWithCoder:decoder];
    if(!self) return nil;
    [txt1 addTarget:self action:@selector(txt1Changed:) forControlEvents:UIControlEventValueChanged];
    [txt2 addTarget:self action:@selector(txt2Changed:) forControlEvents:UIControlEventValueChanged];
    return self;
}
-(void)attachDictionary:(NSMutableDictionary *)dic{
    contentDictionary = dic;
    txt1.text = [contentDictionary valueForKey:@"txt1"];
    txt2.text = [contentDictionary valueForKey:@"txt2"];
}
-(void)txt1Changed:(UITextField *)sender{
    [contentDictionary setValue:txt1.text forKey:@"txt1"];
}
0 голосов
/ 08 сентября 2011

Когда вы создаете соединения IBOutlet в своем подклассе UITableViewCell, подключайте их к свойствам в Владельце файла (viewController) вместо самого представления. Таким образом, вы сможете получить к ним доступ из вашего viewController (UItableViewDataSource)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...