質問

Like many other users, I'm trying to set throw a UITextField into a UITableViewCell to be used for editing a row. But instead of adding a new view, I'm trying to use the accessoryView property. At first I tried this...

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        UITextField *textField =[[UITextField alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 200.0f, 44.0f)];
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.accessoryView = textField;
        [textField becomeFirstResponder];
}

...and the UITextField is added properly, but I need to tap it again to get the keyboard to show. However if I do this...

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        UITextField *textField =[[UITextField alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 200.0f, 44.0f)];
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        [cell addSubview:textField];
        [textField becomeFirstResponder];
}

...it works, the keyboard shows up but, I don't get any of the other benefits of having it as the accessoryView (easier positioning with other views moving around it). I suppose the addSubview: call is altering the responder chain or something and allowing my UITextField to become the first responder, but thought maybe there was another way to do this allowing me to set the cell's accessoryView instead. Thanks.

役に立ちましたか?

解決

I hate my solution, but it works and am up for a better way.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];            

    CGRect detailTextLabelFrame = cell.detailTextLabel.frame;
    detailTextLabelFrame.origin.x -= 100.0f;
    detailTextLabelFrame.size.width += 100.0f;

    UITextField *textField = [[UITextField alloc] initWithFrame:detailTextLabelFrame];

    cell.detailTextLabel.hidden = YES;
    cell.accessoryView = textField;

    // These are the two lines that made it work, but it feels ugly    
    [cell.accessoryView removeFromSuperview];
    [cell addSubview:cell.accessoryView];

    [cell.accessoryView becomeFirstResponder];
}

他のヒント

I hope you know about textfield delegate.Try this way....may be it will help you.

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

if(theTextField == yourtextfieldname) {
    [yourtextfieldname resignFirstResponder];
}

return YES;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top