なんとなく

忘備録です

UITableViewでUITextFieldのカーソル移動を行うメモ

単に、UITextFiledだけのオブジェクトを使うんなら、カーソル移動(入力開始)は

[hogeTextField becomeFirstResponder];

だけで、オッケー。
なんだけど、テーブルを使って、UITableViewCellにセットされたUITextFieldにカーソル移動しようとして
そもそも、どうやってTableセット済のCellの中身を取るのか分からないし…
なので、メモ。

動作は、ログイン画面用のUITableView(0:ユーザーID、1:パスワード)で、ユーザーIDのUITextFieldでReturn→
パスワードTextFieldにカーソル移動。

1) テーブルセルの設定
ViewController.h

// UITextFieldタグ
#define TAG_USER_ID 1
#define TAG_PASSWORD 2
// UITableView-RowIndex
#define ROW_IDX_USERID 0
#define ROW_IDX_PASSWORD 1

// テーブルの列にデータセット
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UILabel *nameLabel;
    UITextField *inputTextFld;
    UIFont *textFont;
   // CGRect *cellRect;
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]
                initWithFrame:CGRectZero reuseIdentifier:CellIdentifier];
    }
    // ラベル
    nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(20.0f, 0.0f, 130.0f, 50.0f)];
    [cell.contentView addSubview:nameLabel];
    
    // テキスト
    inputTextFld = [[UITextField alloc] initWithFrame:CGRectMake(130.0f, 0.0f, 140.0f, 50.0f)];
    inputTextFld.delegate = self;
    
    if (indexPath.row == 0)
    {
        [nameLabel setText:@"ユーザーID"];
        inputTextFld.placeholder = @"ユーザーID";
        inputTextFld.returnKeyType = UIReturnKeyNext;
        // UITextField取得用タグ
        inputTextFld.tag = TAG_USER_ID;
    }
    else
    {
        [nameLabel setText:@"パスワード"];
        inputTextFld.placeholder = @"パスワード";
        inputTextFld.secureTextEntry = YES;
        inputTextFld.tag = TAG_PASSWORD;
    }
    [cell.contentView addSubview:inputTextFld];
    
    return cell;
}

2) テキストフィールドでReturnした時

// TextField Returnタップ
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.tag == TAG_USER_ID)
    {
        // TableのIndexPathリストを取得
        NSArray *indexPathArr = loginInputTbl.indexPathsForVisibleRows;
        // パスワードセルのIndexPathを取得
        NSIndexPath *indexPathPassword = [indexPathArr objectAtIndex:ROW_IDX_PASSWORD];
        // パスワードのセルを取得
        UITableViewCell *cellPass = [loginInputTbl cellForRowAtIndexPath:indexPathPassword];
        UITextField *passText = (UITextField*)[cellPass viewWithTag:TAG_PASSWORD];
        // パスワードの入力開始(カーソルセット)
        [passText becomeFirstResponder];
    }
    else
    {
        // キーボードを閉じる
        [textField resignFirstResponder];
    }
    
    return YES;
}

コレのキモは、設定済のUITableViewCellを取得すること。テーブルを選択してない時に、
設定済のIndexPathを取るのが、最初の問題でしたw

【参考サイト】
☆indexPathからUITableViewCellを取得するには?
http://cheesememo.blog39.fc2.com/blog-entry-291.html

☆UITableViewにUITextFieldを入れる
http://shiffon.dtiblog.com/blog-entry-40.html

☆login using UITableView
http://stackoverflow.com/questions/5063061/login-using-uitableview