iphone пропрограммированно читается из текстового поля - PullRequest
0 голосов
/ 18 февраля 2011

Я создал несколько таблиц с текстовыми полями внутри, как в контактах для iphone, (вдохновлено примером UICatalog)

все работает, но как я могу программно читать значения этих текстовых полей, я вижу, что у них есть тег, но как я могу читать из них (потому что я не могу использовать IB для этого, так как они были созданы программно для перехода внутри таблицы) (нуб тут!)

спасибо,

Я использую некоторый пример стиля hello world, где я набираю текстовое поле таблицы, затем нажимаю кнопку, и набранный текст переходит на метку, Этот пример должен в конечном итоге заполнить мою базу данных coredata из текстовых полей таблицы Как я уже сказал, я preatty noob для этого, так что, пожалуйста, проведите меня через

поэтому, когда пользователь нажимает кнопку Отправить, я получаю текст на метку (и вскоре на coredata)

 - (IBAction) submitYourName;{
lblUserTypedName.text = txtUserName.text;
NSLog(@"received");
 }

это код моего текстового поля

- (UITextField *)textFieldNormal
 {
if (textFieldNormal == nil)
{
    CGRect frame = CGRectMake(kLeftMargin, 8.0, kTextFieldWidth, kTextFieldHeight);
    textFieldNormal = [[UITextField alloc] initWithFrame:frame];

    textFieldNormal.borderStyle = UITextBorderStyleRoundedRect;
    textFieldNormal.textColor = [UIColor blackColor];
    textFieldNormal.font = [UIFont systemFontOfSize:17.0];
    textFieldNormal.placeholder = @"<enter text>";
    textFieldNormal.backgroundColor = [UIColor whiteColor];
    textFieldNormal.autocorrectionType = UITextAutocorrectionTypeNo;    // no auto correction support

    textFieldNormal.keyboardType = UIKeyboardTypeDefault;   // use the default type input method (entire keyboard)
    textFieldNormal.returnKeyType = UIReturnKeyDone;

    textFieldNormal.clearButtonMode = UITextFieldViewModeWhileEditing;  // has a clear 'x' button to the right

    textFieldNormal.tag = kViewTag;     // tag this control so we can remove it later for recycled cells

    textFieldNormal.delegate = self;    // let us be the delegate so we know when the keyboard's "Done" button is pressed

    // Add an accessibility label that describes what the text field is for.
    [textFieldNormal setAccessibilityLabel:NSLocalizedString(@"NormalTextField", @"")];



}   
return textFieldNormal;
   }

и это, чтобы показать это текстовое поле в ячейке таблицы

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
UITableViewCell *cell = nil;

    static NSString *kCellTextField_ID = @"CellTextField_ID";
    cell = [tableView dequeueReusableCellWithIdentifier:kCellTextField_ID];
    if (cell == nil)
    {
        // a new cell needs to be created
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:kCellTextField_ID] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    else
    {
        // a cell is being recycled, remove the old edit field (if it contains one of our tagged edit fields)
        UIView *viewToCheck = nil;
        viewToCheck = [cell.contentView viewWithTag:kViewTag];
        if (viewToCheck)
            [viewToCheck removeFromSuperview];
    }

    UITextField *textField = [[self.dataSourceArray objectAtIndex: indexPath.section] valueForKey:kViewKey];
    [cell.contentView addSubview:textField];



return cell;
}

Ответы [ 3 ]

0 голосов
/ 18 февраля 2011

Когда вы создаете текстовые поля, сохраняйте ссылку на них в переменной экземпляра, например:

UITextField *textField = ...
self.myTextField = textField;
[theSuperview addSubview:self.myTextField];

Затем получите доступ к свойству text вашего экземпляра

NSString *theString = self.myTextField.text;
0 голосов
/ 18 февраля 2011

@ Мако, обратитесь за помощью. Здесь appDelegate - объект вашего класса Application Delegate

// Настройка внешнего вида ячеек табличного представления.

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [self.fieldTable dequeueReusableCellWithIdentifier:CellIdentifier];

         if (cell == nil) {

cell = [self reuseTableViewCellWithIdentifier:CellIdentifier withIndexPath:indexPath];
             }

    // Configure the cell.

        UITextField *txtTemp = (UITextField *)[cell.contentView viewWithTag:1];
    UITextField *txtTemp1 = (UITextField *)[cell.contentView viewWithTag:2];
    UITextField *txtTemp2 = (UITextField *)[cell.contentView viewWithTag:3];
    UITextField *txtTemp3 = (UITextField *)[cell.contentView viewWithTag:4];



                switch (indexPath.section) {
                case 0:
                        switch (indexPath.row) {
                            case 0:

                                txtTemp1.placeholder = @"H/No";
                                appDelegate.HouseNo = [NSString stringWithFormat:@"%@",txtTemp1.text];
                                NSLog(@"%@",appDelegate.HouseNo);
                                break;
                                case 1:
                                txtTemp1.placeholder = @"Street";
                                appDelegate.street = [NSString stringWithFormat:@"%@",txtTemp1.text];
                                NSLog(@"%@", appDelegate.street);
                                break;
                                case 2:
                                txtTemp.placeholder = @"City";
                                txtTemp2.placeholder = @"State";
                                txtTemp3.placeholder = @"Zip Code";
                                appDelegate.city = [NSString stringWithFormat:@"%@",txtTemp.text];
                                NSLog(@"%@",appDelegate.city);
                                appDelegate.state = [NSString stringWithFormat:@"%@",txtTemp2.text];
                                NSLog(@"%@",appDelegate.state);
                                appDelegate.zipCode = [NSString stringWithFormat:@"%@",txtTemp3.text];
                                NSLog(@"%@",appDelegate.zipCode);
                                break;
                                default:
                                break;


                                }
                                break;


    -(UITableViewCell *)reuseTableViewCellWithIdentifier:(NSString *)identifier withIndexPath:(NSIndexPath *)indexPath {


        CGRect cellRectangle = CGRectMake (0, 10, 300, 70); 
        CGRect Field1Frame = CGRectMake (10, 10, 290, 70);
        CGRect Field2Frame = CGRectMake (10, 10, 90, 70);
        CGRect Field3Frame = CGRectMake (110, 10, 95, 70);
        CGRect Field4Frame = CGRectMake (220, 10, 85, 70);
        UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:cellRectangle reuseIdentifier:identifier] autorelease];
        UITextField *textField;
        UITextField *textField1;
        UITextField *textField2;
        UITextField *textField3;

        //Initialize Label with tag 1.

        textField = [[UITextField alloc] initWithFrame:Field2Frame];
        textField.tag = 1;
        [cell.contentView addSubview:textField];



        //Initialize Label with tag 2.

        textField1 = [[UITextField alloc] initWithFrame:Field1Frame];
        textField1.tag = 2;
        [cell.contentView addSubview:textField1];

        //Initialize Label with tag 3.

        textField2 = [[UITextField alloc] initWithFrame:Field3Frame];
        textField2.tag = 3;
        [cell.contentView addSubview:textField2];


        //Initialize Label with tag 4.

        textField3 = [[UITextField alloc] initWithFrame:Field4Frame];
        textField3.keyboardType = UIKeyboardTypeNumberPad;
        textField3.tag = 4;
        [cell.contentView addSubview:textField3];




        [textField release];
        [textField1 release];
        [textField2 release];
        [textField3 release];
        return cell;
    }

Надеюсь, вы понимаете ...Удачи!

0 голосов
/ 18 февраля 2011
UITextField *textField = (UITextField *)[self.view viewWithTag:100];

В зависимости от настроек вы можете заменить self.view на вашу таблицу.

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