UiTableview每第n个结果插入一行

时间:2013-07-29 14:30:42

标签: ios cocoa-touch

我有一个从Json Feed中填充的tableview,行号各不相同。我想要做的是每隔X行插入一个广告。因此,例如,如果Feed返回23行,那么在第5,10,15和20行,我想插入一个包含广告的行。

目前我没有显示代码,因为我真的不知道解决此问题的最佳方法。我预计的一个问题是我添加的行与Json feed的源不同,我认为这可能会导致新行出现问题,因为我不想直接修改数据源,或者至少我认为我不。

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:2)

将NSMutableArray作为插入后者的对象。

int numberofrows;
NSMutableArray *objectsToDisplay;
UITableView *tbleView;

刚刚制作了简单的表格视图,如下所示: -

- (void)viewDidLoad
{
    tbleView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 400) style:UITableViewStylePlain];
    tbleView.delegate=self;
    tbleView.dataSource=self;

    objectsToDisplay=[[NSMutableArray alloc] initWithObjects:@"A ",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",nil];

    numberofrows=[objectsToDisplay count];
    [self.view addSubview:tbleView];

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return numberofrows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *mycell=[tbleView dequeueReusableCellWithIdentifier:@"cellIdentifier"];

    if (mycell==nil) {
        mycell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellIdentifier"];
    }

    mycell.textLabel.text=[objectsToDisplay objectAtIndex:indexPath.row];

    return mycell;
}

要在每5个索引后插入行,请使用此方法

-(IBAction)InsertAdvertizes:(id)sender
{
    for (int i=4;i<numberofrows;i=i+5) {
        [objectsToDisplay insertObject:@"Hello I am Advertize" atIndex:i];
    }

    NSLog(@"object is %@",objectsToDisplay);

    [tbleView reloadData];
}

您的表格看起来像下面显示的图像:---

enter image description here

答案 1 :(得分:0)

使用

tableView: numberOfRowsInSection

设置行的大小

columnsToAdd = round(json.objects.count/5)
return json.objects.count+columnsToAdd

然后在

tableView: cellForRowAtIndexPath

返回您的objectColumns或adColumn

when indexPath.row Modulo 5 != 0 => return yourJsonObjectColumns 
else => return yourAdColumn

我认为这是有道理的。如果您有一些代码,我会再次帮助您。

相关问题