在按钮单击的表视图中添加文本字段

时间:2013-03-15 06:09:04

标签: iphone uitableview addsubview

我有一个表视图,并且在每一行中都有一个添加按钮,点击下面添加的新行我希望onclick行中有一个文本字段,用户可以在其上输入texh你可以帮我怎样在添加行中添加文本字段。 这是我的代码

-(void)buttonclicked:(UIButton *)sender
{

    UIButton *btn = (UIButton *)[self.view viewWithTag:sender.tag];
    NSLog(@"clickedCell=%i", btn.tag);

    [[NSUserDefaults standardUserDefaults]setValue:[NSString stringWithFormat:@"%i", btn.tag] forKey:@"btntag"];
    [self.choices insertObject:@"newrow" atIndex:btn.tag+1];


        [self.tableView reloadData];

}

和表格视图方法

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


    static NSString *CellIdentifier = @"Cell";

    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
     if (cell == nil)
     {


        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }



    UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];
    button.tag = indexPath.row;
    button.frame = CGRectMake(280.0, 10, 25, 30.0); // x,y,width,height

    [button addTarget:self action:@selector(buttonclicked:) forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:button];

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:cell action:nil];
    longPress.delegate = self;
    [cell addGestureRecognizer:longPress];

    int count = 0;
    if(self.editing && indexPath.row != 0)
        count = 1;
    NSLog([NSString stringWithFormat:@"%i,%i",indexPath.row,(indexPath.row-count)]);

    // Set up the cell...
    if(indexPath.row == ([_choices count]) && self.editing)
    {
        cell.textLabel.text = @"ADD";
        return cell;
    }

    NSString *choice = [self.choices objectAtIndex:indexPath.row];

    cell.textLabel.text = choice;



    return cell;
}

1 个答案:

答案 0 :(得分:0)

尝试这样可能对你有帮助,

1.使用一个全局变量类型整数,例如position。

2.当您单击特定按钮 - (void)buttonclicked:(UIButton *)sender方法将调用此方法时,您将btn.tag值分配给该位置。

3.之后您正在重新加载tableview中的表视图cellForRowAtIndexPath方法采取一个条件,如

if(position==indexpath.row)
{
//add your textfield here
}.