在UITableView中动态添加行并设置scrollToRowAtIndexPath

时间:2014-12-16 07:20:17

标签: ios iphone uitableview ios7

在索引路径n-3处单击按钮时动态添加行。在我的表视图中,默认情况下共有六行4包含文本字段,另外两行包含按钮(添加更多和保存)。在最后两行上方的位置添加按钮。

-(void)addMoreButton:(UIButton *)sender
{
rowCount=rowCount+1;

int section = 0;
long row = rowCount;

NSIndexPath* path = [NSIndexPath indexPathForRow:row-3 inSection:section];

[(UITableView *)[self.view viewWithTag:ktagtableView_detailsEdit] beginUpdates];
[(UITableView *)[self.view viewWithTag:ktagtableView_detailsEdit] insertRowsAtIndexPaths:[NSArray arrayWithObjects:path, nil] withRowAnimation:UITableViewRowAnimationLeft];
[(UITableView *)[self.view viewWithTag:ktagtableView_detailsEdit] endUpdates];

    NSIndexPath* top = [NSIndexPath indexPathForRow:rowCount-1 inSection:0];
    [(UITableView*)[self.view viewWithTag:ktagtableView_detailsEdit] scrollToRowAtIndexPath:top atScrollPosition:UITableViewScrollPositionBottom animated:YES];   

}

当rowCount达到8以上并且调用scrollToRowAtIndexPath方法然后调用cellForRowAtIndexPath方法两次时出现问题。 一旦调用了通过索引n-3的insertRowAtIndex,第二次调用了scrollToRowAtIndexPath,它就会传递执行条件的索引n-1

if (indexPath.row == rowCount-1)   //  This is index for last row that contains save button and this condition match thus instead of adding textfields it starts adding save button.


if (indexPath.row == rowCount-2)  //  This is Add more button.

if (indexPath.row < rowCount-2)  //  This is for adding textFields.

请指导以上。并随时询问是否有任何疑问。我被困在最后两天。

更新:cellForRowAtIndexPath方法。

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

NSString *CellIdentifier;
CellIdentifier = [NSString stringWithFormat:@"S%1dR%1d",indexPath.section,indexPath.row];
 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];

CellIdentifier = [NSString stringWithFormat:@"S%1dR%1d",indexPath.section,indexPath.row];
UITextField *textField_SocialProfile;
UIButton *button_AddMore, *button_AddToMyCon;

UIImageView *imageView_Add;

if(cell == nil)
{
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];


    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    [cell setBackgroundColor:[UIColor clearColor]];

    linelable=[[UILabel alloc]initWithFrame:CGRectMake(0, cell.contentView.frame.size.height+9, cell.contentView.frame.size.width, 0.5)];
    [cell.contentView addSubview:linelable];
    [linelable setBackgroundColor:[UIColor colorWithRed:(152.0f/255.0f) green:(152.0f/255.0f) blue:(152.0f/255.0f) alpha:0.2f]];

    if (indexPath.row < rowCount-2)
    {
        textField_SocialProfile = [[UITextField alloc]init];
        textField_SocialProfile.tag=indexPath.row+501;
        NSLog(@"textField_SocialProfile.tag %ld",(long)textField_SocialProfile.tag);

        textField_SocialProfile.frame = CGRectMake(70, (tableView.rowHeight - 20)/2, 230, 30);
        textField_SocialProfile.delegate = self;
        textField_SocialProfile.borderStyle = UITextBorderStyleRoundedRect;

        switch (indexPath.row) {
            case 0:
                textField_SocialProfile.attributedPlaceholder = [[NSAttributedString alloc] initWithString:ktagInstagram attributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor]}];
                break;
            case 1:
                textField_SocialProfile.attributedPlaceholder = [[NSAttributedString alloc] initWithString:ktagFacebook attributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor]}];
                break;
            case 2:
                textField_SocialProfile.attributedPlaceholder = [[NSAttributedString alloc] initWithString:ktagTwitter attributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor]}];
                break;
            case 3:
                textField_SocialProfile.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Linkedin" attributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor]}];
                break;
            default:
                textField_SocialProfile.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Social Networking" attributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor]}];
        }

        textField_SocialProfile.textColor = [UIColor colorWithRed:(152.0f/255.0f) green:(152.0f/255.0f) blue:(152.0f/255.0f) alpha:1.0f];
        textField_SocialProfile.layer.cornerRadius = 5.0;
        textField_SocialProfile.clipsToBounds = YES;

        [textField_SocialProfile.layer setBorderColor:[UIColor lightGrayColor].CGColor];
        [textField_SocialProfile.layer setBorderWidth:0.5];


    if (intEditSave==1) {
        [textField_SocialProfile setUserInteractionEnabled:NO];
    }
    else
    {
        [textField_SocialProfile setUserInteractionEnabled:YES];
    }

        imageView_Add = [[UIImageView alloc]init];

        switch (indexPath.row) {
            case 0:
                imageView_Add.image = [UIImage imageNamed:@"instagramIcon.png"];
                textField_SocialProfile.text=@"www.instagram.com/";

                if (dataSourceArray.count > indexPath.row) {
                    textField_SocialProfile.text = [[dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"SocialProfile"];
                    if ([[NSString stringWithFormat:@"%@",[[dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"SocialProfile"]] length] != 0) {
                        textField_SocialProfile.text=[[dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"SocialProfile"];
                         if([textField_SocialProfile.text isEqualToString:@""])
                        {
                            textField_SocialProfile.text=[NSString stringWithFormat:@"www.instagram.com/%@",[[dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"SocialProfile"]];
                        }
                    }else{
                        textField_SocialProfile.text=@"www.instagram.com/";
                    }
                }

                break;
            case 1:
                imageView_Add.image = [UIImage imageNamed:@"facebokIcon.png"];
                textField_SocialProfile.text=@"www.facebook.com/";

                if (dataSourceArray.count > indexPath.row) {
                    textField_SocialProfile.text = [[dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"SocialProfile"];
                    if ([[NSString stringWithFormat:@"%@",[[dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"SocialProfile"]] length] != 0) {
                        textField_SocialProfile.text=[[dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"SocialProfile"];
                        if([textField_SocialProfile.text isEqualToString:@""])
                        {
                            textField_SocialProfile.text=[NSString stringWithFormat:@"www.facebook.com/%@",[[dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"SocialProfile"]];
                        }
                    }else{
                        textField_SocialProfile.text=@"www.facebook.com/";
                    }
                }                    break;
            case 2:
                imageView_Add.image = [UIImage imageNamed:@"twitterIcon.png"];
                textField_SocialProfile.text=@"www.twitter.com/";

                if (dataSourceArray.count > indexPath.row) {
                    textField_SocialProfile.text = [[dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"SocialProfile"];
                    if ([[NSString stringWithFormat:@"%@",[[dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"SocialProfile"]] length] != 0) {
                        textField_SocialProfile.text=[[dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"SocialProfile"];
                         if([textField_SocialProfile.text isEqualToString:@""])
                        {
                            textField_SocialProfile.text=[NSString stringWithFormat:@"www.twitter.com/%@",[[dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"SocialProfile"]];
                        }
                    }else{
                        textField_SocialProfile.text=@"www.twitter.com/";
                    }
                }                    break;
            case 3:
                imageView_Add.image = [UIImage imageNamed:@"linkedinIcon.png"];
                textField_SocialProfile.text=@"www.linkedin.com/";

                if (dataSourceArray.count > indexPath.row) {
                    textField_SocialProfile.text = [[dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"SocialProfile"];
                    if ([[NSString stringWithFormat:@"%@",[[dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"SocialProfile"]] length] != 0) {
                        textField_SocialProfile.text=[[dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"SocialProfile"];
                         if([textField_SocialProfile.text isEqualToString:@""])
                        {
                            textField_SocialProfile.text=[NSString stringWithFormat:@"www.linkedin.com/%@",[[dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"SocialProfile"]];
                        }
                    }else{
                        textField_SocialProfile.text=@"www.linkedin.com/";
                    }
                }                    break;
            default:
                imageView_Add.image = [UIImage imageNamed:@"myconIcon.png"];
                if (dataSourceArray.count > indexPath.row) {

                    textField_SocialProfile.text = [[dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"SocialProfile"];}

                break;

        }

        NSString *socialName= textField_SocialProfile.text;


        switch (indexPath.row) {
            case 0:
                if ([socialName rangeOfString:@"www.instagram.com/"].location!=NSNotFound) {
                    imageView_Add.image = [UIImage imageNamed:@"instagramIcon.png"];
                }
                else if ([socialName rangeOfString:@"www.linkedin.com/"].location!=NSNotFound)
                {
                    imageView_Add.image = [UIImage imageNamed:@"linkedinIcon.png"];
                }
                else if ([socialName rangeOfString:@"www.facebook.com/"].location!=NSNotFound)
                {
                    imageView_Add.image = [UIImage imageNamed:@"facebokIcon.png"];
                }
                else if ([socialName rangeOfString:@"www.twitter.com/"].location!=NSNotFound)
                {
                    imageView_Add.image = [UIImage imageNamed:@"twitterIcon.png"];
                }
                else
                {
                    imageView_Add.image = [UIImage imageNamed:@"myconIcon.png"];
                }

                break;
            case 1:
                if ([socialName rangeOfString:@"www.instagram.com/"].location!=NSNotFound) {
                    imageView_Add.image = [UIImage imageNamed:@"instagramIcon.png"];
                }
                else if ([socialName rangeOfString:@"www.linkedin.com/"].location!=NSNotFound)
                {
                    imageView_Add.image = [UIImage imageNamed:@"linkedinIcon.png"];

                }
                else if ([socialName rangeOfString:@"www.facebook.com/"].location!=NSNotFound)
                {
                    imageView_Add.image = [UIImage imageNamed:@"facebokIcon.png"];

                }
                else if ([socialName rangeOfString:@"www.twitter.com/"].location!=NSNotFound)
                {
                    imageView_Add.image = [UIImage imageNamed:@"twitterIcon.png"];

                }
                else
                {
                    imageView_Add.image = [UIImage imageNamed:@"myconIcon.png"];
                }
                break;
            case 2:
                if ([socialName rangeOfString:@"www.instagram.com/"].location!=NSNotFound) {
                    imageView_Add.image = [UIImage imageNamed:@"instagramIcon.png"];
                }
                else if ([socialName rangeOfString:@"www.linkedin.com/"].location!=NSNotFound)
                {
                    imageView_Add.image = [UIImage imageNamed:@"linkedinIcon.png"];
                }
                else if ([socialName rangeOfString:@"www.facebook.com/"].location!=NSNotFound)
                {
                    imageView_Add.image = [UIImage imageNamed:@"facebokIcon.png"];

                }
                else if ([socialName rangeOfString:@"www.twitter.com/"].location!=NSNotFound)
                {
                    imageView_Add.image = [UIImage imageNamed:@"twitterIcon.png"];

                }
                else
                {
                    imageView_Add.image = [UIImage imageNamed:@"myconIcon.png"];
                }
                break;
            case 3:
                if ([socialName rangeOfString:@"www.instagram.com/"].location!=NSNotFound) {
                    imageView_Add.image = [UIImage imageNamed:@"instagramIcon.png"];
                }
                else if ([socialName rangeOfString:@"www.linkedin.com/"].location!=NSNotFound)
                {
                    imageView_Add.image = [UIImage imageNamed:@"linkedinIcon.png"];

                }
                else if ([socialName rangeOfString:@"www.facebook.com/"].location!=NSNotFound)
                {
                    imageView_Add.image = [UIImage imageNamed:@"facebokIcon.png"];

                }
                else if ([socialName rangeOfString:@"www.twitter.com/"].location!=NSNotFound)
                {
                    imageView_Add.image = [UIImage imageNamed:@"twitterIcon.png"];
                }
                else
                {
                    imageView_Add.image = [UIImage imageNamed:@"myconIcon.png"];
                }
                break;
            default:
                if ([socialName rangeOfString:@"www.instagram.com/"].location!=NSNotFound) {
                    imageView_Add.image = [UIImage imageNamed:@"instagramIcon.png"];
                }
                else if ([socialName rangeOfString:@"www.linkedin.com/"].location!=NSNotFound)
                {
                    imageView_Add.image = [UIImage imageNamed:@"linkedinIcon.png"];

                }
                else if ([socialName rangeOfString:@"www.facebook.com/"].location!=NSNotFound)
                {
                    imageView_Add.image = [UIImage imageNamed:@"facebokIcon.png"];

                }
                else if ([socialName rangeOfString:@"www.twitter.com/"].location!=NSNotFound)
                {
                    imageView_Add.image = [UIImage imageNamed:@"twitterIcon.png"];
                }
                else
                {
                    imageView_Add.image = [UIImage imageNamed:@"myconIcon.png"];
                }
                break;
        }


        imageView_Add.frame = CGRectMake(30, (tableView.rowHeight - 8)/2, 15, 15);
        textField_SocialProfile.font = [UIFont fontWithName:@"arial" size:15.0];

        [cell addSubview:imageView_Add];
        imageView_Add = Nil;
        [cell addSubview:textField_SocialProfile];
        //textField_SocialProfile = Nil;

    }

    else if(indexPath.row == rowCount-2)//Add more button
    {
        //        NSLog(@"textf: %@",textF.text);

        NSLog(@"AddMore: %ld",indexPath.row);
        NSLog(@"AddMore: %d",rowCount);

        button_AddMore = [[UIButton alloc]init];
        [button_AddMore setTitle:ktagAdd_More forState:UIControlStateNormal];
        [button_AddMore titleLabel].font = [UIFont fontWithName:@"arial" size:15.0];
        [button_AddMore setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button_AddMore addTarget:self action:@selector(addMoreButton:) forControlEvents:UIControlEventTouchUpInside];
        button_AddMore.tag = ktagbutton_AddMore;

        button_AddMore.frame = CGRectMake(90, (cell.frame.size.height-20)/2, 140, 30);
        button_AddMore.center=CGPointMake(90+70, 22);
        [button_AddMore setBackgroundImage:[UIImage imageNamed:@"addMore_button.png"] forState:UIControlStateNormal];
        [cell addSubview:button_AddMore];
        linelable.hidden=NO;

        if(intEditSave == 1)//Editing is complete
        {
            button_AddMore.enabled=NO;
        }
        else
        {
            button_AddMore.enabled=YES;
        }
    }
    else if(indexPath.row == rowCount-1)//Save fields button
    {
        NSLog(@"Save: %ld",indexPath.row);
        NSLog(@"Save: %d",rowCount);

        button_AddToMyCon = [[UIButton alloc]init];
        [button_AddToMyCon setTitle:ktagAdd_to_MyCon forState:UIControlStateNormal];
        [button_AddToMyCon titleLabel].font = [UIFont fontWithName:@"arial" size:15.0];
        [button_AddToMyCon setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button_AddToMyCon addTarget:self action:@selector(save_Fields:) forControlEvents:UIControlEventTouchUpInside];
        button_AddToMyCon.tag = ktagbutton_AddToMyCon;

        button_AddToMyCon.frame = CGRectMake(90, (cell.frame.size.height-20)/2, 140, 30);
        button_AddToMyCon.center=CGPointMake(90+70, 22);

        [button_AddToMyCon setBackgroundColor:[UIColor colorWithRed:(234.0f/255.0f) green:(134.0f/255.0f) blue:(59.0f/255.0f) alpha:1.0]];
        button_AddToMyCon.layer.cornerRadius=4;
        [cell addSubview:button_AddToMyCon];
        linelable.hidden=YES;

    }

}
    return cell;
}

问题是如果我将dequeReusable属性设置为nil,那么这个问题就解决了,滚动时当前数据开始消失。

1 个答案:

答案 0 :(得分:0)

这是tableView数据源和委托方法的行为。 cellForRowAtIndexPath时会调用scrollToRowAtIndexPath方法,因为当表格滚动显示屏幕上不可见的单元格时,方法会执行重复单元格,因此cellForRowAtIndexPath会为新的可见单元格加载内容。

这是默认和正确的行为,你不能通过它。

现在您需要使用它来管理应用程序需求。我不认为这种行为会对您的要求产生任何循环漏洞。

因为cellForRowAtIndexPath是一个被多次调用的方法,所以你不能在这里限制任何约束。如果您认为未达到预期的行为,请留言。

修改

在为您创建示例演示时,我想出了一点 - 可能会很快解决您的问题。

在下面的行中,动画无效:

[(UITableView *)[self.view viewWithTag:ktagtableView_detailsEdit] insertRowsAtIndexPaths:[NSArray arrayWithObjects:path, nil] withRowAnimation:UITableViewRowAnimationLeft];

将行动态UITableViewRowAnimationLeft更改为UITableViewRowAnimationAutomatic,请参阅以下更新的行:

[(UITableView *)[self.view viewWithTag:ktagtableView_detailsEdit] insertRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];

如果这不能解决您的问题,那么您可以在此处获得示例演示......

为了简单起见,我限制了控制并专注于功能。

Dynamic Cell Creation Demo - Click Here

enter image description here