はじめに
TableView下部の余分なSeparatorの消し方についてです。(Objective-C)
TableViewを使うとき、いつも忘れてしまって参考書やらネットやらを見直すので書き残します。
今回は、余分なSeparator消しということに絞っているため
TableViewの実装に関して詳しくは触れませんのでご了承下さい。
とりあえずTableViewを作成してみる
Storyboard利用して作成しました。
Storyboard
Storyboard上では、いつも通り。
TableViewを用意して、更にTableViewCellを乗せて
TableViewCellのReuse Identifierを設定(今回は「Cell」と設定)しただけ。
Source code
ViewController.m
#import "ViewController.h"
@interface ViewController () <UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic) NSArray *data;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"たいとるううう";
//Cellに表示する文字列
_data = @[@"hoge", @"poco", @"piyo"];
//Delegate
_tableView.delegate = self;
_tableView.dataSource = self;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _data.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}
cell.textLabel.text = _data[indexPath.row];
return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// 選択状態の解除
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
@end
実行結果
Cellは3つだけなのに余分なSeparatorがいっぱい、、
解決策
たった1行追加するだけで解決できちゃうんです!!
- (void)viewDidLoad内に次の1行を追加します。
_tableView.tableFooterView = [UIView new];
たったこれだけで、解決しちゃうんです!
先ほどのSource codeのviewDidLoadに追加してみると、
Source code
ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"たいとるううう";
//Cellに表示する文字列
_data = @[@"hoge", @"poco", @"piyo"];
//Delegate
_tableView.delegate = self;
_tableView.dataSource = self;
//下部の余分なセパレータを表示しないために、TableViewのFooterViewを生成
_tableView.tableFooterView = [UIView new];
}
実行結果
最後に
今回は、Objective-CでTableView下部の余分なSeparatorの消し方について書いてみました。
tableFooterViewを生成する方法以外にも、もっと良い方法をご存知という方はご教授願います。