[iOS SDK] UITableView の上に広告ネットワーク(320x50)を追加した際に、セルが隠れないように余白を設定する
先週、リリースしたアプリ「郵便番号検索くん」は、無料アプリ+広告ネットワークでアプリを収益化しています。広告ネットワークは、AppBank Network を利用しています。AppBank Network は、数ある広告ネットワークの中でも導入が簡単なのでオススメです。
さて、このアプリでは、下図のようにテーブルビューの上に広告(320x50)を配置しています。
UIViewController の self.view に、UITableView, UIView(広告)を addSubView しています。その際、テーブルビューに余白を設定しないと次のようにコンテンツが隠れてしまいます。沖縄県が、広告の下にもぐりこんでしまっています。
UITableView に広告を加えているアプリで、コンテンツが隠れてしまっている残念な例がたくさん見受けられるので、この記事では、セルを隠れないようにして、幸せになる方法を紹介します。
そもそも、UITableView のサイズを広告の上までにすれば解決できるのですが、それだと広告ネットワークの通信が終わるまで、テーブルビューのコンテンツが浮くことになるので見た目がよくありません。
UITableView の上に広告ネットワークを表示させた際に、セルが隠れないように余白を付ける
新規プロジェクト Single View Application で作成したものをテンプレートにコードを書いていきます。余白の設定方法はこんな感じです。
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
@end
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
CGRect rect = self.view.frame;
UITableView *tableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
tableView.delegate = self;
tableView.dataSource = self;
// UITableView のコンテンツに余白を付ける(下50px)
tableView.contentInset = UIEdgeInsetsMake(0.f, 0.f, 50.f, 0.f);
// UITableView のスクロール可能範囲に余白を付ける(下50px)
tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0.f, 0.f, 50.f, 0.f);
[self.view addSubview:tableView];
UIView *adView = [[UIView alloc] initWithFrame:CGRectMake(0.f, rect.size.height - 50.f, 320.f, 50.f)];
adView.backgroundColor = [UIColor blackColor];
[self.view addSubview:adView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 100;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [NSString stringWithFormat:@"%d", indexPath.row + 1];
return cell;
}
@end
UITableView の contentInset と scrollIndicatorInsets でうまいことしています。ここでは、広告ネットワークで一般的な高さである 50px の余白を空けています。
UIEdgeInsetsMake は、(上, 右, 下, 左)の余白を設定します。
実行結果は、こんな感じです。
ちなみに、Interface Builder で、テーブルビューを貼りつけている場合は、サイズインスペクタから、この余白設定を行えます。
また、UIWebView も次のようにすれば、余白を設定できます。
webView.scrollView.contentInset = UIEdgeInsetsMake(0.f, 0.f, 44.f, 0.f);
webView.scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0.f, 0.f, 44.f, 0.f);
下図は、iPhone / iPad アプリ Quicka の内蔵ブラウザで使用している一例です。