tableView中动态添加,删除行

当时在项目中完成的效果是,我在Footer中放了一个按钮,能动态生成行,并且绑定相应的文本框和删除按钮
下面实现该效果:
//setting section of number
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
//返回视图行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [arrayRow count];
}

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

{
   
    NSString * nul = [NSString stringWithFormat:@"cell%d",indexPath.row];
    UITableViewCell *Cell = [tableView dequeueReusableCellWithIdentifier:nul];
    //Cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    Cell.textLabel.textAlignment = UITextAlignmentLeft;
    if(Cell == nil){
        Cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero
                                       reuseIdentifier:nul] autorelease];
        //add a Text
        UITextField *textEmail = [[UITextField alloc] initWithFrame:CGRectMake(30, 10, 231, 31)];
        textEmail.placeholder = @"input E-mail";
        textEmail.font = [ UIFont systemFontOfSize:14 ];
        textEmail.keyboardType = UIKeyboardTypeEmailAddress;
        textEmail.returnKeyType  =UIReturnKeyDone;
        textEmail.tag = indexPath.row;
        [textEmail addTarget:self action:@selector(cancelKeyBoard:) forControlEvents:UIControlEventEditingDidEnd];
   
        //add a button
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.contentMode = UIViewContentModeScaleToFill;
        UIImage *img = [UIImage imageNamed:@"BAG.png"];
        [btn setBackgroundImage:img forState:UIControlStateNormal];
        [btn setTitle:@"Button Title" forState:UIControlStateNormal];
        [btn setTag:[indexPath row]];
        [btn addTarget:self action:@selector(deletePressed:)  forControlEvents:UIControlEventTouchUpInside];
        btn.frame = CGRectMake(261, 10, 20, 20);
        [Cell.contentView addSubview:textEmail];
        [Cell.contentView addSubview:btn];
        Cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [textEmail release];
    }
    return Cell;
}

UIButton *addBtn;
//add row in tableview and datasourse
- (IBAction) addPressed:(id)sender
{
    addBtn = (UIButton*)sender;
    [arrayRow addObject:@"Add"];
    if ([arrayRow count] ==4) {
        [sender setHidden:YES];
    }
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:[arrayRow count]-1 inSection:0];
    [self.tableViewEmail insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

//delete row in tableview and datasourse
-(void)deletePressed:(id)sender
{
    if ([arrayRow count] ==1) {
        return;
    }
    if ([arrayRow count] <= 4) {
        [addBtn setHidden:NO];
    }
  

你可能感兴趣的:(tableView中动态添加,删除行)