0

1 つのセクションと 2 つのセルを持つ UITableView を使用してログイン画面を作成しました。これが、これらの細胞が作成される方法です。後でこれらのセルから値を取得する方法がわかりません。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIdentifier = @"LoginCellIdentifier";

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
        UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 25)];
        leftLabel.backgroundColor = [UIColor clearColor];
        leftLabel.tag = 1;
        [cell.contentView addSubview:leftLabel];
        [leftLabel release];

        UITextField *valueTextField = [[UITextField alloc] initWithFrame:CGRectMake(120, 10, 400, 35)];
        valueTextField.tag = 2;
        valueTextField.delegate = self;
        [cell.contentView addSubview:valueTextField];
        [valueTextField release];
    }

    if (indexPath.row == 0) {   // User name
        UILabel *lblText = (UILabel *)[cell.contentView viewWithTag:1];
        lblText.text = @"Username: ";

        UITextField *userNameField = (UITextField *)[cell.contentView viewWithTag:2];
        userNameField.placeholder = @"Enter your username here";        
    }
    else {  // Pass word
        UILabel *lblText = (UILabel *)[cell.contentView viewWithTag:1];
        lblText.text = @"Password: ";

        UITextField *passwordField = (UITextField *)[cell.contentView viewWithTag:2];
        passwordField.placeholder = @"Enter your password here";
        passwordField.secureTextEntry = YES;
    }

    return cell;
}

return正確には、ユーザーがキーを押したときに値を取得したい。だから、ここでセルのテキストフィールドの値を取得したい...

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    NSLog(@"%@ is the Value", textField.text);
    [textField resignFirstResponder];

    return YES;
}

しかし、それらのテキスト フィールドの値を取得する方法がわかりません。この場合、インデックスパスの cellForRowAtIndexPath が機能するのだろうか?

4

2 に答える 2

2

@gnuchutextFieldDidEndEditing:で言及されている方法を使用する必要がありますが、編集を終了したばかりのテキストフィールドを検出するには、次のコードを使用できます。

- (void)textFieldDidEndEditing:(UITextField *)textField {
    UITableViewCell *cell = (UITableViewCell *)[[textField superview] superview];
    UITableView *table = (UITableView *)[cell superview];
    NSIndexPath *textFieldIndexPath = [table indexPathForCell:cell];
    NSLog(@"Row %d just finished editing with the value %@",textFieldIndexPath.row,textField.text);
}

上記のコードはうまくいくはずですが、2 つの固定セルに UITableView を使用するのはやり過ぎであり、コードが不必要に複雑になるだけです。IMO では、2 つのラベルと 2 つのテキストフィールドを持つ標準ビューを使用した方がよいでしょう。これは、Interface Builder またはコードで簡単に作成でき、作業が大幅に簡素化されます。

于 2011-03-14T13:17:36.980 に答える
1

UITextFieldDelegate を実装する必要があります (ドキュメント リンクはこちら)。そうすれば、

- (void)textFieldDidEndEditing:(UITextField *)textField

ユーザーがテキストフィールドの編集を終了したときに起動するメソッド。

于 2011-03-14T12:35:53.657 に答える