2014年1月2日木曜日

セグエを使わずに実現する

前回の内容をセグエを使わずに実現する。 また、ビューコントローラについてはView Controllerのみを使い、ストーリボードについては2つ使ってみる。つまり、iOS View Controllerプログラミングガイドのリスト 2-3のような形式をとってみる。


新しいストーリーボードからビューコントローラのインスタンスを生成する。
#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UIViewController *viewController;

@end
#import "AppDelegate.h"
#import "ViewController.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:NSStringFromClass([ViewController class]) bundle:nil];
    ViewController *viewController = [storyboard instantiateInitialViewController];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
    self.viewController = navigationController;
    self.window.rootViewController = navigationController;
    
    [self.window makeKeyAndVisible];
    return YES;
}

@end


選択行をスムーズに消すために、viewWillAppear:イベントメソッド内でdeselectRowAtIndexPath: animated:メソッドを呼び出す。
セルを再利用のためにdequeueReusableCellWithIdentifier:メソッドを使う。
画面遷移については、didSelectRowAtIndexPath:イベントメソッド内で実行する。
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>

@end
#import "ViewController.h"
#import "DetailViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation ViewController {
    @private
    NSArray *_leagueKinds;
    NSArray *_leagues;
    NSArray *_leaguePrefixes;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
 // Do any additional setup after loading the view.
    _leagueKinds = @[@"セントラル・リーグ", @"パシフィック・リーグ"];
    
    _leagues = @[
                 @[@"ジャイアンツ", @"タイガース", @"ドラゴンズ", @"ベイスターズ", @"カープ", @"スワローズ"],
                 @[@"バッファローズ", @"ホークス", @"ファイターズ", @"マリーンズ", @"ライオンズ", @"ゴールデンイーグルス"]
                 ];
    
    _leaguePrefixes = @[
                        @[@"読売", @"阪神", @"中日", @"横浜DeNA", @"広島東洋", @"東京ヤクルト"],
                        @[@"オリックス", @"福岡ソフトバンク", @"北海道日本ハム", @"千葉ロッテ", @"埼玉西武", @"東北楽天"]
                        ];
    
    self.title = @"日本プロ野球チーム";
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.tableView deselectRowAtIndexPath:self.tableView.indexPathForSelectedRow animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return [_leagueKinds count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [_leagues[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    
    NSArray *teams = _leagues[indexPath.section];
    NSArray *teamPrefixes = _leaguePrefixes[indexPath.section];
    cell.textLabel.text = teams[indexPath.row];
    cell.detailTextLabel.text = teamPrefixes[indexPath.row];
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString *HeaderIdentifier = @"Header";
    UITableViewHeaderFooterView *view = [tableview dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    
    if (!view) {
        view = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
    }
    
    view.textLabel.text = _leagueKinds[section];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *teams = _leagues[indexPath.section];
    NSArray *teamPrefixes = _leaguePrefixes[indexPath.section];
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:NSStringFromClass([DetailViewController class]) bundle:nil];
    DetailViewController *detailViewController = [storyboard instantiateInitialViewController];
    [detailViewController setTitle:teams[indexPath.row]];
    [detailViewController setDetailItem:teamPrefixes[indexPath.row]];
    [self.navigationController pushViewController:detailViewController animated:YES];
}

@end

[参考URL]
iOS View Controllerプログラミングガイド

2013年12月28日土曜日

iOSで詳細ビューを追加する


前回作成したテーブルビューから遷移する詳細ビューを追加する。
詳細ビューとして、ストーリーボードにView Controller(紐づけるクラス名はDetailViewControllerとする)を追加する。

Table View Controller(クラス名:ViewController)からView Controller(クラス名:DetailViewController)へのセグエを設定する。
Storyboard Segue: 「identifier」に"getDetail"と入力、「Style」に"push"を選択する。


Table View Controller(クラス名:ViewController)のバックボタン表示名を変更する
Navigation Item: 「Back Button」に"プロ野球"と入力する。


詳細ビュー(クラス名:DetailViewController)をコーディングする。
#import <UIKit/UIKit.h>

@interface DetailViewController : UIViewController

@property (weak, nonatomic) IBOutlet UILabel *detailLabel;
@property (strong, nonatomic) NSString *detailItem;

@end
#import "DetailViewController.h"

@implementation DetailViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.detailLabel.text = self.detailItem;
    NSLog(@"self.detailItem is %@", self.detailItem);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end


テーブルビュー(クラス名:ViewController)をコーディングする。
ViewController.mにおいてDetailViewController.hをインポートし、prepareForSegue: sender:メソッドを追加する。
#import "ViewController.h"
#import "DetailViewController.h"

@interface ViewController ()

@end

@implementation ViewController {
    @private
    NSArray *_leagueKinds;
    NSArray *_leagues;
    NSArray *_leaguePrefixes;
}

#pragma mark - Navigation

// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([[segue identifier] isEqualToString:@"getDetail"]) {

        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        NSArray *teams = _leagues[indexPath.section];
        NSArray *teamPrefixes = _leaguePrefixes[indexPath.section];
        
        [[segue destinationViewController] setTitle:teams[indexPath.row]];
        [[segue destinationViewController] setDetailItem:teamPrefixes[indexPath.row]];
    }   
}
@end

2013年12月23日月曜日

iOSでテーブルビューを使う


環境
  • Xcode 5.0.2
  • ARC ON
  • iOSシミュレータ 7.0

ストーリーボードにNavigation ControllerとTable View Controllerを追加する。

Table View Cell: 「Style」から"Subtitle"を選択、「Identifier」に"Cell"と入力する。

この紐付けをしておかないと実行時に下記エラーが吐かれる。
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'


Navigation Item: 「Title」に"日本プロ野球チーム"と入力する。


UITableViewControllerを継承したクラス(今回の例ではViewController)を作成する。

tableView: cellForRowAtIndexPath:メソッドとtableView: viewForHeaderInSection:メソッドはテーブルビュー初回描画時と画面スクロールが発生するたびに呼ばれる。
#import <UIKit/UIKit.h>

@interface ViewController : UITableViewController

@end
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController {
    @private
    NSArray *_leagueKinds;
    NSArray *_leagues;
    NSArray *_leaguePrefixes;
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    _leagueKinds = @[@"セントラル・リーグ", @"パシフィック・リーグ"];
    
    _leagues = @[
                @[@"ジャイアンツ", @"タイガース", @"ドラゴンズ", @"ベイスターズ", @"カープ", @"スワローズ"],
                @[@"バッファローズ", @"ホークス", @"ファイターズ", @"マリーンズ", @"ライオンズ", @"ゴールデンイーグルス"]
                ];
    
    _leaguePrefixes = @[
                       @[@"読売", @"阪神", @"中日", @"横浜DeNA", @"広島東洋", @"東京ヤクルト"],
                       @[@"オリックス", @"福岡ソフトバンク", @"北海道日本ハム", @"千葉ロッテ", @"埼玉西武", @"東北楽天"]
                       ];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return [_leagueKinds count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [_leagues[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

//    if (!cell) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
//    }
 
    NSArray *teams = _leagues[indexPath.section];
    NSArray *teamPrefixes = _leaguePrefixes[indexPath.section];
    cell.textLabel.text = teams[indexPath.row];
    cell.detailTextLabel.text = teamPrefixes[indexPath.row];
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString *HeaderIdentifier = @"Header";
    UITableViewHeaderFooterView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    
    if (!view) {
        view = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
    }
    
    view.textLabel.text = _leagueNames[section];

    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

@end

2013年11月13日水曜日

gitリポジトリを引っ越す

mirrorオプションをつけて実行する。
$ git clone --mirror git@before.example.com:hogeuser/Sample.git
$ cd Sample.git
$ git push --mirror git@after.example.net:foouser/Sample.git

[参考URL]
What's the difference between git clone --mirror and git clone --bare

2013年10月28日月曜日

Homebrewをアンインストールする

デフォルト設定で使っている場合は、下記を実行してHomebrewをアンインストールする。
$ brew doctor
$ brew update
$ git clone https://gist.github.com/1173223.git
$ cd 1173223/
$ chmod u+x uninstall_homebrew.sh
$ sh ./uninstall_homebrew.sh

必要に応じて、さらに下記を実行する。
$ rm -rf /usr/local/Cellar /usr/local/.git && brew cleanup

[参考URL]
How do I uninstall Homebrew?

2013年9月9日月曜日

Node.jsバージョン管理ツールを導入する(Windows編)

Windowsで利用可能なNode.jsバージョン管理ツールは複数あるが、ここでは個人的に最も使い勝手の良いと思われるnodistの導入方法について説明する。

プロキシ環境下にある場合は過去の内容を参考にプロキシ設定する。
$ git config --global http.proxy http://proxy.example.com:8080
$ git config --global https.proxy http://proxy.example.com:8080
$ git config --global url."https://".insteadOf git://

nodistをインストールする。
$ git clone git://github.com/marcelklehr/nodist.git

PATHを通すために、下記の通りシステム環境変数をセットする(下記は該当箇所のみ抜粋)。
変数
Path %HOMEDRIVE%%HOMEPATH%\nodist\bin

64bit環境の場合は下記の通りシステム環境変数をセットする。
変数
NODIST_X64 1

プロキシ環境下にある場合は下記の通りシステム環境変数をセットする。なお、nodist内部でHTTPS_PROXYはHTTP_PROXYに置換されるようなので、現状、HTTPS_PROXYについては設定しなくても問題ないと思われる。
変数
HTTP_PROXY http://proxy.example.com:8080
HTTPS_PROXY http://proxy.example.com:8080

nodist依存関係ファイルをインストールする。
> nodist update

動作確認する。
> nodist -v
0.3.8

Node.jsの最新安定版をインストールしてみる。
> nodist dist
> nodist stable
0.10.18

使用するNode.jsのバージョンを指定する。
> nodist 0.10.18
> node -v
v0.10.18

Node.jsバージョン管理ツールを導入する

OS Xで利用可能なNode.jsバージョン管理ツールは複数あるが、ここでは個人的に最も使い勝手の良いと思われるnodebrewの導入方法について説明する。

プロキシ環境下にある場合は下記の通りプロキシ設定する。
$ vim ~/.bashrc
$ source ~/.bashrc

~/.bashrc
# proxy
export http_proxy="http://proxy.example.com:8080"
export https_proxy="http://proxy.example.com:8080"

nodebrewをインストールする。
$ curl -L git.io/nodebrew | perl - setup

PATHを通す。
$ vim ~/.bashrc
$ source ~/.bashrc

~/.bashrc
# nodebrew
NODEBREW_ROOT=$HOME/.nodebrew
export NODBREW_ROOT
# PATH
PATH=$PATH:${NODEBREW_ROOT}/current/bin

動作確認する。
$ nodebrew -v
nodebrew 0.6.3

Node.jsの最新安定版をインストールしてみる。
$ nodebrew ls-remote
$ nodebrew install-binary stable
fetch: http://nodejs.org/dist/v0.10.18/node-v0.10.18-darwin-x64.tar.gz

使用するNode.jsのバージョンを指定する。
$ nodebrew use v0.10.18
$ node -v
v0.10.18


補足

私の環境では.bash_profileで.bashrcファイルを読み込むようにしている。

~/.bash_profile
source ~/.bashrc