その後のその後

iOSエンジニア 堤 修一のブログ github.com/shu223

リッチなポップアップメニューをさくっと実現できる OGActionChooser

たかがモック、されどモック。
モックといえど、RoundRect タイプのボタンを使用してたりするとどうにもテンションが上がらない、ということはよくあります。(僕はよくあります)


そんなわけで、リッチな GUI を簡単に作れる系のUIコンポーネントをいろいろ cocoa controls で探してきては手順をここにメモっておこう、と思い立った次第です。


第一弾は OGActionChooser 。


こういうポップアップメニューを簡単に表示できるようになります。



導入方法

1. ソースコードをダウンロード
https://github.com/relikd/OGActionChooser


2. プロジェクトにファイルを追加
OGActionChooser.h, OGActionChooser.m をプロジェクトに追加します。


3. ヘッダをインポート
#import "OGActionChooser.h"


4. プロトコルへの準拠


5. デリゲートメソッドを実装
OGActionChooserDelegate の actionChooser:buttonPressedWithIndex: と actionChooserFinished: を実装します。


サンプルコードではこんな感じで実装されています。

- (void)actionChooser:(OGActionChooser *)ac buttonPressedWithIndex:(NSInteger)index
{
	switch (index) {
		case 0:
			ac.shouldDrawShadow = !ac.shouldDrawShadow; break;
		case 2:
			ac.backgroundColor = [UIColor colorWithRed:rand()%255/255.0 
												 green:rand()%255/255.0 
												  blue:rand()%255/255.0 alpha:0.8f];
			break;
		case 6:
			NSLog(@"first button on the second page clicked"); break;
		default:
			NSLog(@"clicked button with index: %i", index);
	}
}

- (void)actionChooserFinished:(OGActionChooser *)ac
{
	NSLog(@"cancel button clicked or dismissed programatically");
}


6. 表示処理を実装
OGActionButton オブジェクトを必要な数だけつくって、OGActionChooser に NSArray 型で渡します。


サンプルコードではこんな感じ。

- (void)showActionSheet:(UIButton*)sender
{
	OGActionChooser *acSheet = [OGActionChooser actionChooserWithDelegate:self];
	acSheet.title = @"Chooser title";
	
	OGActionButton *fst = [OGActionButton buttonWithTitle:@"Toggle Shadow" 
												imageName:@"actionChooser_Button" 
												  enabled:YES];
	OGActionButton *snd = [OGActionButton buttonWithTitle:@"Change Color" 
												imageName:@"actionChooser_Button" 
												  enabled:YES];
	OGActionButton *trd = [OGActionButton buttonWithTitle:@"Next Page" 
												imageName:@"actionChooser_Button.png" 
												  enabled:YES];
	
	[acSheet setButtonsWithArray:[NSArray arrayWithObjects:
								  fst, @"", snd, // always three in a row (currently)
								  @"", @"", @"",
								  trd, nil]]; // next page
	[acSheet presentInView: sender.superview];
}


デフォルトでは 1 ページに 2 行 x 3 列の 6 つのボタンが乗り、@"" と空の文字列を配列に入れることで空欄を設けられるようです。


たとえば上記サンプルのように空文字列を配列に入れると、下記のように2つめのメニューボタンの位置が空欄で表示されます。



カスタマイズ

OGActionChooser.m の中身を見ると、冒頭に次のような定義が並んでいます。

#define ScrollViewEdgePadding 10
#define ActionButtonPaddingX 4
#define ActionButtonPaddingY 4
#define ActionButtonSizeX 84
#define ActionButtonSizeY 94
#define maxColumns 3
#define maxRows 2

このあたりをいじると、各ページのボタンの数や並び方の変更、レイアウトの微調整などが行えそうです。


・・・と思いこんなふうに変えてみましたが

#define ActionButtonSizeX 42
#define ActionButtonSizeY 47
#define maxColumns 6
#define maxRows 4

各メニューボタンのサイズは変わったものの、カラム数などは変わらず、でした。


列数、行数を可変にするにはコードに手を入れる必要がありそうです。(もともと定数定義されているのもコード内なのですが・・・)