简体   繁体   English

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

[英]Adding rows dynamically in UITableView and setting scrollToRowAtIndexPath

Dynamically adding rows on click of a button at index path n-3. 单击索引路径n-3上的按钮可动态添加行。 In my table view by default there are total six rows 4 contains textfields and other two contains button(Add more and Save). 默认情况下,在我的表格视图中,共有六行4包含文本字段,另外两行包含按钮(添加更多并保存)。 Adding buttons at location above last two rows. 在最后两行上方的位置添加按钮。

-(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];   

}

The problem arises when rowCount reaches more than 8 and scrollToRowAtIndexPath method called then cellForRowAtIndexPath method is called twice. 当rowCount超过8并且调用scrollToRowAtIndexPath方法然后调用cellForRowAtIndexPath方法两次时,就会出现问题。 Once called by insertRowAtIndex that passes index n-3 and second time when scrollToRowAtIndexPath is called it passes index n-1 that runs the condition when 一旦被insertRowAtIndex调用并传递索引n-3,并且第二次调用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.

Please guide for above. 请指导以上。 And feel free to ask if any query. 并随时询问是否有任何查询。 I am stuck in it from last two days. 最近两天以来,我一直陷于困境。

Update: cellForRowAtIndexPath method. 更新: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;
}

The trouble is if i set dequeReusable property to nil, then this problem solves and current data starts vanishing when scrolled. 问题是如果我将dequeReusable属性设置为nil,则此问题将解决,滚动时当前数据开始消失。

This is a behaviour of tableView datasource and delegate methods. 这是tableView数据源和委托方法的行为。 cellForRowAtIndexPath method is called when scrollToRowAtIndexPath because when table scroll to show cell which is not visible on screen then method performs reuse cell, So cellForRowAtIndexPath load content for new visible cells. scrollToRowAtIndexPath时将调用cellForRowAtIndexPath方法,因为当表滚动以显示屏幕上不可见的单元格时,该方法将执行重用单元格,因此cellForRowAtIndexPath为新的可见单元cellForRowAtIndexPath载内容。

It is default and correct behaviour, you can not by pass it. 这是默认的正确行为,您不能通过它。

Now you need to manage app requirement with it. 现在,您需要使用它来管理应用程序需求。 I don't think so that this behaviour makes any loop hole to your requirement. 我认为这种行为不会给您的需求带来任何麻烦。

Because cellForRowAtIndexPath is a method which is called several times and you can not limit any constraints here. 因为cellForRowAtIndexPath是被多次调用的方法,所以您不能在此处限制任何约束。 Still leave a comment if you think that your expected behaviour is not achieved. 如果您认为未实现预期的行为,请继续发表评论。

Edit: 编辑:

While creating a sample demo for you, I figure out one point - may be it will sort out your problem quickly. 在为您创建示例演示时,我指出了一点-可能会很快解决您的问题。

In below line animation was not working proper: 在下面的行中,动画无法正常工作:

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

Change row animation UITableViewRowAnimationLeft to UITableViewRowAnimationAutomatic , see below updated line: 将行动画UITableViewRowAnimationLeft更改为UITableViewRowAnimationAutomatic ,请参见以下更新的行:

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

Still if this will not solve your problem you have sample demo here... 仍然,如果这不能解决您的问题,您可以在此处获取示例演示...

For the sake of simplicity I have limit control and focus on functionality. 为了简单起见,我限制了控制并专注于功能。

Dynamic Cell Creation Demo - Click Here 动态单元创建演示-单击此处

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM