2012-02-13 3 views
0

Я создал пользовательскую ячейку с текстовым полем, но я не могу получить ее значение.
В моем таблицеView есть 3 из этих пользовательских ячеек вместе с другими ячейками по умолчанию.
Когда я пытаюсь это:, возвращающее значение null из текста ячейкиField

NSString *string = customCell.textField.text; 

Я всегда получаю нулевое значение ...
Это мой код:

TextFieldCell.m

#import "TextFieldCell.h" 

@implementation TextFieldCell 

@synthesize label; 
@synthesize textField; 

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{ 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) 
    { 
     label = [[UILabel alloc] initWithFrame:CGRectZero]; 
     label.backgroundColor = [UIColor clearColor]; 
     label.textAlignment = UITextAlignmentRight; 
     label.textColor = [UIColor blackColor]; 
     label.font = [UIFont boldSystemFontOfSize:16.0]; 
     label.adjustsFontSizeToFitWidth = YES; 
     label.baselineAdjustment = UIBaselineAdjustmentNone; 
     label.numberOfLines = 20; 
     [self.contentView addSubview:label]; 

     textField = [[UITextField alloc] initWithFrame:CGRectZero]; 
     textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; 
     textField.backgroundColor = [UIColor clearColor]; 
     textField.font = [UIFont boldSystemFontOfSize:16.0]; 
     textField.delegate = self; 
     textField.returnKeyType = UIReturnKeyDone; 
     [self.contentView addSubview:textField]; 
    } 

    return self; 
} 

-(void)layoutSubviews 
{ 
    [super layoutSubviews]; 

    CGRect r = CGRectInset(self.contentView.bounds, 8, 8); 
    CGRect r1 = CGRectInset(self.contentView.bounds, 8, 8); 

    if (label.text != nil) 
    { 
     r.size = CGSizeMake(12, 27); 
     label.frame = r; 

     r1.origin.x += self.label.frame.size.width + 6; 
     r1.size.width -= self.label.frame.size.width + 6; 
     textField.frame = r1; 
    } 
    else 
    { 
     textField.frame = r; 
    } 
} 

-(BOOL)textFieldShouldReturn:(UITextField *)aTextField 
{ 
    [textField resignFirstResponder]; 
    return NO; 
} 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated 
{ 
    [super setSelected:selected animated:animated]; 
} 

@end 

Просмотр таблицы данных Источник

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (indexPath.section == 0) 
    { 
     if (indexPath.row == 0) 
     { 
      return [self textFieldCellForTableView:tableView atIndexPath:indexPath]; 
     } 
     else if (indexPath.row == 1) 
     { 
      return [self textFieldCellForTableView:tableView atIndexPath:indexPath]; 
     } 
     else 
     { 
      return [self defaultCellForTableView:tableView atIndexPath:indexPath]; 
     } 
    } 
    else if (indexPath.section == 1) 
    { 
     if (indexPath.row == 0) 
     { 
      return [self textFieldCellForTableView:tableView atIndexPath:indexPath]; 
     } 
     else 
     { 
      return [self defaultCellForTableView:tableView atIndexPath:indexPath]; 
     } 
    } 
    else if (indexPath.section == 2) 
    { 
     return [self defaultCellForTableView:tableView atIndexPath:indexPath]; 
    } 
    else 
    { 
     return [self chooseFotoCellForTableView:tableView atIndexPath:indexPath]; 
    } 
} 

-(TextFieldCell *)textFieldCellForTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *TextFieldCellIdentifier = @"TextFieldCellIdentifier"; 

    TextFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:TextFieldCellIdentifier]; 
    if (cell == nil) 
    { 
     cell = [[[TextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TextFieldCellIdentifier] autorelease]; 
     cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    } 

    if (indexPath.section == 0) 
    { 
     if (indexPath.row == 0) 
     { 
      cell.label.text = nil; 
      cell.textField.placeholder = NSLocalizedString(@"Nome", @""); 
     } 
     else 
     { 
      cell.label.text = [[NSLocale currentLocale] objectForKey:NSLocaleCurrencySymbol]; 
      cell.textField.placeholder = NSLocalizedString(@"Costo", @""); 
     } 
    } 
    else 
    { 
     cell.label.text = nil; 
     cell.textField.placeholder = NSLocalizedString(@"URL", @""); 
    } 

    return cell; 
} 

Код для повтора Рив TextField Значение

TextFieldCell *nomeCell = (TextFieldCell *)[self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; 
TextFieldCell *costoCell = (TextFieldCell *)[self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]]; 
TextFieldCell *linkCell = (TextFieldCell *)[self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]]; 

NSLog(@"nomeCell textField = %@", nomeCell.textField.text); 
NSLog(@"costoCell textField = %@", costoCell.textField.text); 
NSLog(@"linkCell textField = %@", linkCell.textField.text); 

Я попытался войти nomeCell, costoCell и linkCell и они правильно выделены и инициализируется, и я не использую ARC здесь ...
Может кто-нибудь мне помочь?
Большое вам спасибо!

ответ

1

Я предполагаю, что вы на самом деле введен некоторый текст в текстовом поле к тому времени, вы пытаетесь получить значение, и вы запрашиваете значение чтобы обновить вашу модель данных, а не полагаться на представление/ячейки таблицы для хранения ваших данных?

Не удается получить текущую ячейку, вызвав ваш контроллер табличного вида tableView:cellForRowAtIndexPath:. Это нужно вызывать только табличным представлением, когда ему нужна новая ячейка.

Вызовите метод cellForRowAtIndexPath: непосредственно на столе. Вместо этого:

TextFieldCell *nomeCell = (TextFieldCell *)[self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; 

ли это:

TextFieldCell *nomeCell = (TextFieldCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; 
+0

Спасибо так много! Вы решили мою проблему;) – matteodv

0

Вы назначаете текст placeholder и регистрируете textField.text.

0
textField = [[UITextField alloc] initWithFrame:CGRectZero]; 
     textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; 
     textField.backgroundColor = [UIColor clearColor]; 
     textField.font = [UIFont boldSystemFontOfSize:16.0]; 
     textField.delegate = self; 

     //added 
     textField.tag = 101; 

     textField.returnKeyType = UIReturnKeyDone; 
     [self.contentView addSubview:textField]; 

код Чтобы восстановить TextField значения:

//fetch cell for which you want to get textfield then, 
TextFieldCell *nomeCell = (TextFieldCell *)[cell.contentView viewWithTag:101]; 
Смежные вопросы