
source
ViewController.h
- を追記してtable関連の関数を処理できるようにする
...
@interface ViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>
...
ViewController.m
#import "ViewController.h"
#import "TACell.h"
#import <QuartzCore/QuartzCore.h>
@interface ViewController (){
NSMutableArray *items;
}
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (weak, nonatomic) IBOutlet UIButton *plusButton;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//テーブル関連
items = [NSMutableArray array];
[items addObject:@"うんこ"];
[items addObject:@"べんぴ"];
[items addObject:@"うんこ2"];
_myTableView.delegate = self;
_myTableView.dataSource = self;
[_myTableView registerNib:[UINib nibWithNibName:NSStringFromClass([TACell class]) bundle:nil] forCellReuseIdentifier:@"cell"];
//ボタンデザイン関連
[[_plusButton layer] setBorderColor:[[UIColor blackColor] CGColor]];
[[_plusButton layer] setBorderWidth:1.0];
[[_plusButton layer] setCornerRadius:10.0];
[_plusButton setClipsToBounds:YES];
}
//ボタン:編集ボタン
- (IBAction)editButtonClicked:(id)sender {
if (_myTableView.editing){
[_myTableView setEditing:NO animated:YES];
} else {
[_myTableView setEditing:YES animated:YES];
}
}
//ボタン:追加ボタン
- (IBAction)addButtonClicked:(id)sender {
// push :addIndex = 0;
// unshift :addIndex = items.count;
int addIndex = 0;
[items insertObject:@"New!!" atIndex:addIndex];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:addIndex inSection:0];
NSArray *indexPaths = [NSArray arrayWithObjects:indexPath,nil];
[_myTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
}
// テーブル関連の処理
//テーブル:ヘッダー
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section{
return @"データ1 データ2 データ3";
}
//テーブル:セクション数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
//テーブル:行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section {
return items.count;
}
//テーブル:編集可能か?
-(BOOL)tableView:(UITableView*)tableView canEditRowAtIndexPath:(NSIndexPath*)indexPath
{
return YES;
}
//テーブル:データ生成
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath{
TACell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil) { // yes
NSLog(@"null");
}
cell.titleLabel.text = [NSString stringWithFormat:@"%@", items[indexPath.row]];
NSLog(@"make %d",indexPath.row);
NSLog(@"%@", items[indexPath.row]);
return cell;
}
// テーブル:削除を押した時の処理
-(void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete){
// 配列を削除
[items removeObjectAtIndex:indexPath.row];
// UITableView から削除
[_myTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationAutomatic];
}
}