将TextField视为UICell的子视图

时间:2012-06-20 22:08:00

标签: ios xcode

我已将TextField添加到UICell,以允许用户更改所述单元格的TextLabel。一切正常,键盘出现,当我按回车键时,TextLabel变为正确的值。但是,我不能看到正在编辑的文本。这是我的代码:

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {


     [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
     UITableViewCell *aCell = [self.tableView cellForRowAtIndexPath:indexPath];
     NSString *aCategory = aCell.textLabel.text;
     [[aCell detailTextLabel] setText:aCategory];


     [aCell setEditing:YES animated:YES];
     UITextField *userText =[[UITextField alloc] init];
     userText.tag = indexPath.row;
     [aCell addSubview:userText];
     NSArray *test =[aCell subviews];
     NSLog(@"I have %d many subviews",[test count]);
     userText.alpha=1.0;
     [userText setDelegate:self];
     userText.autocorrectionType = UITextAutocorrectionTypeNo;
     [aCell bringSubviewToFront:userText];
     [userText becomeFirstResponder];


 }

如果可能,我想在没有自定义单元格的情况下执行此操作。提前谢谢。

1 个答案:

答案 0 :(得分:0)

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    UITableViewCell *aCell = [self.tableView cellForRowAtIndexPath:indexPath];
    NSString *aCategory = aCell.textLabel.text;
    [[aCell detailTextLabel] setText:aCategory];

    UITextField *userText = [[UITextField alloc] initWithFrame:aCell.textLabel.frame];
    userText.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    userText.font = aCell.textLabel.font;
    userText.text = aCell.textLabel.text;
    aCell.textLabel.text = nil;
    userText.tag = indexPath.row;
    [aCell addSubview:userText];

    [userText setDelegate:self];
    userText.autocorrectionType = UITextAutocorrectionTypeNo;
    [aCell bringSubviewToFront:userText];
    [userText becomeFirstResponder];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:textField.tag inSection:0];
    UITableViewCell *aCell = [self.tableView cellForRowAtIndexPath:indexPath];
    aCell.textLabel.text = textField.text;
    [textField removeFromSuperview];
}

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