首页 > 解决方案 > 显示横幅广告的问题 Objective-C

问题描述

我在为第 1 行和每 5 行显示 BannerAd 时遇到问题。在显示数据时,第一行被横幅广告替换,每 5 行数据被横幅广告替换......如何克服这个问题。以下是我尝试过的。TIA

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger n;
    n= [array count];
    return n;
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row % 5 == 0) {
        //configure ad cell

        for(UIView* view in cell.contentView.subviews) {
            if([view isKindOfClass:[GADBannerView class]]) {
                [view removeFromSuperview];
            }
        }
else
{
 Title.text=[NSString stringWithFormat:@"%@ ",[dict objectForKey:@"Name"]];
}
return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row % 5 == 0)
        return 60;
    else
        return 153;
}

标签: iosobjective-ciphoneadmobtableview

解决方案


您需要增加返回的单元格数量numberOfRowsInSection并考虑添加的行cellForRowAt

广告数量为 1 + n/5(第一行,然后每 5 行),因此表格中的单元格数量为n + n/5 + 1

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger n;
    n= [array count];
    return n/5 + n + 1;
}

现在,您需要从中返回的一些单元格cellForRowAt将是广告,您在访问数据数组时需要考虑到这一点。您需要的索引是行号——它之前的广告行数。这是 index/5 + 1(第一行和每 5 行)。

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row % 5 == 0) {
        AdCell *cell = (AdCell *)[tableView dequeueReusableCellWithIdentifier:"Ad" forIndexPath: indexPath];
        ...
        NSLog(@"Showing an ad at row %ld",indexPath.row);
        return cell;
    else
    {
        NSInteger index = indexPath.row - indexPath.row/5 - 1;
        NSDictionary *dict = myArray[index];
        NormalCell *cell = (NormalCell *)[tableView dequeueReusableCellWithIdentifier:"Normal" forIndexPath: indexPath];
        cell.title.text=[NSString stringWithFormat:@"%@ ",dict["Name"]];
        NSLog(@"Showing a normal row at row %ld (data from element %ld of array)",indexPath.row,index);
        return cell;
   }
}

推荐阅读